简体   繁体   English

如何在到达下一行之前等待 Promise.all() 完成?

[英]How to wait for Promise.all() to complete before reaching next line?

I'm learning Node.js.我正在学习 Node.js。

I have to call an async function work() inside my Promise.all() loop and it must be completed before moving on to statements that are after the Promise.all().我必须在我的Promise.all()循环中调用异步 function work()并且必须在继续执行 Promise 之后的语句之前完成它。 Currently, it reaches the FINISH statment before completing work() .目前,它在完成work()之前到达FINISH语句。

What is the right way to make the code wait for work() function to complete?让代码等待 work() function 完成的正确方法是什么?

 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()

It's hard to tell what you're really after here, but don't mix and match await and then , in general.很难说你在这里真正追求的是什么,但一般来说,不要混搭awaitthen

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();

prints out (the first lines with various delays)打印出来(第一行有各种延迟)

some work here 1
some work here 2
some work here 3
[ 2, 4, 6 ]

I think you forgot the "await" before calling your work() function.我认为你在调用你的 work() function 之前忘记了“等待”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM