Sub*_*kar 0 javascript node.js promise async-await
我正在学习 Node.js。
我必须在循环work()内调用异步函数Promise.all(),并且必须在继续执行 Promise.all() 之后的语句之前完成该函数。目前,它到达了FINISH未完成的状态work()。
让代码等待 work() 函数完成的正确方法是什么?
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
async function work() {
await new Promise((resolve, reject) => {
setTimeout(resolve, 2000, 'foo');
})
console.log('some work here')
}
async function main() {
await Promise.all([promise1, promise2, promise3]).then((values) => {
values.forEach(function(item) {
console.log(item)
work()
});
});
console.log('FINISH')
}
main()Run Code Online (Sandbox Code Playgroud)
很难说你在这里真正想要什么,但一般来说不要混合await搭配。then
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function work(value) {
await delay(1000 * value);
console.log("some work here", value);
await delay(1000);
return value * 2;
}
async function main() {
// Doesn't really do much, since these are already resolved...
const values = await Promise.all([promise1, promise2, promise3]);
// Pass all of those values to `work`, which returns a promise,
// and wait for all of those promises to resolve.
const workedValues = await Promise.all(values.map(work));
console.log(workedValues);
}
main();
Run Code Online (Sandbox Code Playgroud)
打印出来(第一行有各种延迟)
some work here 1
some work here 2
some work here 3
[ 2, 4, 6 ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2444 次 |
| 最近记录: |