Promise.all调用充满函数的数组变量

时间:2017-04-22 17:09:08

标签: javascript

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);
    })
]

3 个答案:

答案 0 :(得分:1)

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

除非有理由想要生成一堆必须执行的函数,否则只需生成promises就更简单了:

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

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

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

答案 1 :(得分:0)

如果您期望这个结果,那么请确保您正在调用承诺:

body {
    background-color: red;
}

注意:const stuffArray = whatToGet.map(thing => getMyFunction(thing)()); 我们实际上是从getMyFunction(thing)()调用返回的匿名函数,以便达到实际的承诺。

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

getMyFunction

答案 2 :(得分:-2)

而不是:

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

使用:

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