为了账号安全,请及时绑定邮箱和手机立即绑定

js控制异步输出顺序

js控制异步输出顺序

哈士奇WWW 2019-08-05 23:02:27
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?
查看完整描述

2 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

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);
})();
                            
查看完整回答
反对 回复 2019-08-05
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

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);
}
)();
}
                            
查看完整回答
反对 回复 2019-08-05
  • 2 回答
  • 0 关注
  • 451 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信