在我们开发中会遇到一些关于数据异步交互的问题,比如打印一些东西先从一个地方拿到数据然后在进行打印,有时候小伙伴们可能会遇到我的打印页面出来了,或者数据还没有传输过来就打印出来了。我们可以通过js中的宏任务和微任务来进行解决。
1.注册宏任务
一般可以将打印任务注册为宏任务 而数据交互放在宏任务外
#打印方法
printTables(){
print({
printable: 'printJS-form',
type: 'html',
// scanStyles: false,
style: 'table tr td,th { border-collapse: collapse;padding: 0 10px;border:1px solid}',
targetStyles: ['*'],
maxWidth:1100
})
},
//数据交互方法
CreateOneFormPage(msg) {
this.printData=msg
priceSlips.queryAllDetails(this.printData.oId,this.queryPriceSheet.pName,
this.queryPriceSheet.odType,0,0)
.then(res=>{
this.priceSheetList=res.list
//通过settimeout将打印任务注册为宏任务
setTimeout(()=>{
this.printTables()
},0)
})
}
2.注册微任务
通过new promise 注册一个微任务,在new promise中是同步代码块,而在.then中是异步的要在同步代码块执行完毕后,才会去执行。
CreateOneFormPage(msg) {
new Promise((resolve,reject)=>{
this.printData=msg
priceSlips.queryAllDetails(this.printData.oId,this.queryPriceSheet.pName,
this.queryPriceSheet.odType,0,0)
.then(res=>{
this.priceSheetList=res.list
resolve()
})
}).then(()=>{
this.printTables()
})
},