class Test {
constructor() {
const nums = [1, 2, 3];
(async() => {
for(let i of nums) {
let x = await this.print(i);
console.log(x);
}
})();
}
print(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x);
}, 1000);
})
}
}
const test = new Test();
(async() => {
let x4 = await test.print(4);
console.log(x4);
let x5 = await test.print(5);
console.log(x5);
})();
怎样才能做到顺序输出 1 2 3 4 5 ?
Test类增加一个cprm属性,用来接收构造函数里面的异步调用,值是Promise类型。然后在调用输出4之前await这个cprm属性,就可以等到构造函数的123都输出完成后再输出4。