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);})();
蝴蝶刀刀
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);})();}
添加回答
举报
0/150
提交
取消