链接多个 Promise.all() 语句

use*_*481 5 javascript

我是 JavaScript 新手,很难链接多个 Promise.all() 语句。下面是我的代码的高度简化版本。

function a(x) {
   return new Promise(function(resolve) { 
       setTimeout(resolve(x*2), 500)
   });
}

function b(x) {
   return new Promise(function(resolve) { 
       setTimeout(resolve(x*3), 400)
   });
}

function c(x) {
    const promises = [a(x),b(x)];
    Promise.all(promises).then(function(y){
        z = y[0] + y[1]
        return new Promise(function(resolve, reject){
            resolve(z);
        });
    }); 
}

function d(x) {
    const promises = [];
    for (let input of x){
        promises.push(c(input))
    }
    Promise.all(promises).then(function(z){
        console.log(z);
    });
}

const data = [1,2,3,4,5];
d(data);
Run Code Online (Sandbox Code Playgroud)

我希望看到这个打印出来:

[5, 10, 15, 20, 25]
Run Code Online (Sandbox Code Playgroud)

但我看到的是这样的:

[undefined, undefined, undefined, undefined, undefined]
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

Cer*_*nce 6

c函数目前没有返回任何内容,导致undefined. 相反,return调用Promise.all并在Promise.all解析后返回,y[0] + y[1]以便(in ).then的使用者可以访问解析后的值。cd

另外,避免显式的 Promise 构造反模式- 如果您已经有一个Promise可以使用的,则不需要调用new Promise来构造一个单独的。相反,只需调用.then现有的Promise.

function c(x) {
    const promises = [a(x),b(x)];
    return Promise.all(promises).then(function(y){
        return y[0] + y[1]
    }); 
}
Run Code Online (Sandbox Code Playgroud)

function c(x) {
    const promises = [a(x),b(x)];
    return Promise.all(promises).then(function(y){
        return y[0] + y[1]
    }); 
}
Run Code Online (Sandbox Code Playgroud)