谁能帮助我了解 .spread 在 Bluebird 库中的用途

Can anyone help me understand what is the use of .spread in Bluebird library

我正在开发我的第一个 Nodejs 应用程序,其他人在我之前开发了这个应用程序,我正在尝试解决一些问题并且无法理解以下内容。

return Promise.join(
        findStagingAdvanced(stagingQuery),
        findDboAdvanced(dboQuery)
    )     
    .spread((stagingIssues, dboIssues) => _.concat(dboIssues, stagingIssues))
    .then(....) 

它允许你得到 findStagingAdvancedfindDboAdvanced 的结果,并在没有中间变量的情况下将它们合并在一起[=13​​=]

如果没有传播,您将有一个额外的变量会发生变异:

var staging;
findStagingAdvanced(stagingQuery)
.then(stagingQuery => {
    staging = stagingQuery; // not that good practice
    return findDboAdvanced(dboQuery);
})
.then(dboQuery => {
    var merged = [staging, dboQuery];
    return ... // another promise that use staging and dboQuery together
})

如果您有一个用数组实现的承诺,并且该数组的长度已知,那么您可以使用 .spread() 将数组转换为单独的函数参数。它是 .then() 的替代品,在调用处理程序之前将参数从数组转换为单个参数。

所以,而不是这个:

someFunction().then(function(arrayOfArgs) {
    let arg1 = arrayOfArgs[0];
    let arg2 = arrayOfArgs[1];
});

你可以这样做:

someFunction().spread(function(arg1, arg2) {
    // can directly access arg1 and arg2 here 
});

因此,在您的特定代码示例中,Promise.join() 已经提供了一个回调来分隔各个结果,因此根本不需要它。所以,你可以这样做:

return Promise.join(
        findStagingAdvanced(stagingQuery),
        findDboAdvanced(dboQuery),
        (stagingIssues, dboIssues) => _.concat(dboIssues, stagingIssues)
    ).then(allIssues => {
        // allIssues contains combined results of both functions above
    });

此代码所做的是从 findStagingAdvanced()findDboAdvanced() 收集结果并将这些结果合并到一个结果数组中。


它可以用标准 ES6 编写(例如,没有 Bluebird 的额外功能),如下所示:

 return Promise.all([findStagingAdvanced(stagingQuery), findDboAdvanced(dboQuery)])
   .then(results => results[0].concat(results[1]))
   .then(allIssues => {
        // allIssues contains combined results of both functions above
    });