提问者:小点点

resolve函数对于promise构造函数是必需的吗?


null

const promiseArray = [1, 2, 3].map(num =>
  new Promise(async resolve => {
    while (num > 0) {
      await foo();
      num--;
    }
    await bar(num);
    resolve(); // No value to return
  })
);
const a = Promise.all(promiseArray);

是否有必要使用resolve函数?

我们能省略它,把承诺变成这样吗?

const promiseArray = [1, 2, 3].map(num =>
  new Promise(async () => {
    while (num > 0) {
      await foo();
      num--;
    }
    await bar(num);
  })
);
const a = Promise.all(promiseArray);

共3个答案

匿名用户

null

我认为您与异步/等待和承诺混淆了。

当您指定异步函数时,它将总是返回已解决的允诺,除非您在函数内部抛出错误,而该错误没有被捕获。

null

async function hello(){ return 1}
hello().then((val) => console.log(val));

您可以使用承诺来实现相同的示例

let promise = return new Promise((resolve) => return resolve(1));
promise.then((val) => console.log(val));

匿名用户

是的,当使用New promise构造函数时,调用ResolveReject是必要的,否则promise将保持挂起状态。

但是,在您的情况下,根本不应该使用New Promise:

const promiseArray = [1, 2, 3].map(async num => {
  while (num > 0) {
    await foo();
    num--;
  }
  await bar(num);
});
const a = Promise.all(promiseArray);

匿名用户

我们能省略它,把承诺变成这样吗?

null

const a = Promise.all(promiseArray);

PromiseArray中的任何承诺都不会解决。 因此,承诺a将永远无法解决。 因此,这些都没有用,您将无法知道什么时候所有的事情都完成了执行。

看来你真的不需要在承诺中包涵任何东西。 你可以这样做:

async function runLoop() {
    for (let i = 1; i <= 3; i++) {
        let num = i;
        while (num > 0) {
          await foo();
          num--;
        }
        await bar(num);    // note this will always be bar(0)
    }
}

runLoop().then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

或者,如果希望单独的循环并行运行,可以这样做:

const promiseArray = [1, 2, 3].map(async num => {
  while (num > 0) {
    await foo();
    num--;
  }
  await bar(num);    // note this will always be bar(0)
});
Promise.all(promiseArray).then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});