js控制异步输出顺序

classTest{
constructor(){
constnums=[1,2,3];
(async()=>{
for(letiofnums){
letx=awaitthis.print(i);
console.log(x);
}
})();
}
print(x){
returnnewPromise((resolve,reject)=>{
setTimeout(()=>{
resolve(x);
},1000);
})
}
}
consttest=newTest();
(async()=>{
letx4=awaittest.print(4);
console.log(x4);
letx5=awaittest.print(5);
console.log(x5);
})();
怎样才能做到顺序输出12345?
哈士奇WWW
浏览 454回答 2
2回答

互换的青春

Test类增加一个cprm属性,用来接收构造函数里面的异步调用,值是Promise类型。然后在调用输出4之前await这个cprm属性,就可以等到构造函数的123都输出完成后再输出4。classTest{constructor(){constnums=[1,2,3];this.cprm=(async()=>{for(letiofnums){letx=awaitthis.print(i);console.log(x);}})();}print(x){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve(x);},1000);})}}consttest=newTest();(async()=>{awaittest.cprm;letx4=awaittest.print(4);console.log(x4);letx5=awaittest.print(5);console.log(x5);})();

蝴蝶刀刀

classTest{constructor(){constnums=[1,2,3];this.init=Promise.all(nums.map(asyncn=>console.log(awaitthis.print(n,true))));}print(x,isInit=false){return(isInit?Promise.resolve():this.init).then(()=>newPromise((resolve,reject)=>{setTimeout(()=>{resolve(x);},1000);}));}}consttest=newTest();(async()=>{letx4=awaittest.print(4);console.log(x4);letx5=awaittest.print(5);console.log(x5);})();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript