【问题标题】:Promise.all invoking array variable full of functions [duplicate]Promise.all 调用充满函数的数组变量[重复]
【发布时间】:2017-04-22 17:09:08
【问题描述】:

function getMyFunction(data) {
    return () => new Promise((resolve, reject) => {
        resolve('here is the value:' + data);
    });
}
const whatToGet = [
    'a',
    'b',
    'c',
    'd',
    'e',
];
const stuffArray = whatToGet.map(thing => getMyFunction(thing));
Promise.all(stuffArray).then((result) => {
    console.log('result: ', result);
});

期待

result: [
    'here is the value: a',
    'here is the value: b',
    'here is the value: c',
    'here is the value: d',
    'here is the value: e'
]

但我却得到了结果:

result:  [ () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    }), () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    }), () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    }), () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    }), () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    })
]

【问题讨论】:

  • 你只是问了基本相同的问题并得到了适当的答案
  • @charlietfl 完全不同的问题。
  • 不,不是……基本原理是完全一样的,只是不是传递一个函数,而是返回一个函数数组……所有这些都需要被调用,或者其他人建议只返回承诺
  • 老实说,这个功能似乎是多余的......虽然如果你在上一条评论中准确地询问了你提出的问题......并链接到其他问题,也许不会被认为是同一个问题。或者只是向原始回答者寻求帮助

标签: javascript


【解决方案1】:

您将一组函数传递给Promise.all,但它需要一组承诺。

除非出于某种原因您想要生成一堆必须执行的函数,否则只生成 Promise 会更简单:

function getMyPromise(data) {
    return new Promise((resolve, reject) => {
        resolve('here is the value:' + data);
    });
}

那么这应该可以正常工作:

const stuffArray = whatToGet.map(getMyPromise);
Promise.all(stuffArray).then((result) => {
    console.log('result: ', result);
});

旁注/protip:如果您想为特定值创建承诺,请不要使用new Promise。只需使用Promise.resolve

function getMyPromise(data) {
    return Promise.resolve('here is the value:' + data);
}

【讨论】:

    【解决方案2】:

    如果你期待这个结果,那么请确保你调用了承诺:

    const stuffArray = whatToGet.map(thing => getMyFunction(thing)());
    

    注意:getMyFunction(thing)() 我们实际上是从 getMyFunction 调用返回的匿名函数,以达到实际的承诺。

    或者,如果您想使用当前代码,请确保 getMyFunction 返回一个承诺而不是返回承诺的函数:

    function getMyFunction(data) {
        return new Promise((resolve, reject) => {
            resolve('here is the value:' + data);
        });
    }
    

    【讨论】:

      【解决方案3】:

      代替:

      Promise.all(stuffArray).then((result) => {
          console.log('result: ', result);
      });
      

      用途:

      Promise.all(stuffArray.map(func => func())).then((result) => {
          console.log('result: ', result);
      });
      

      【讨论】:

        猜你喜欢
        • 2015-10-25
        • 1970-01-01
        • 2013-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多