有没有人知道如何为这个异步JavaScript代码建立一个似乎合理的承诺链:
更新
var arr1 = firstFunc(input1, function(err, res){
if(err) return err;
return res;
});
var arr2 = firstFunc(input2, function(err, res){
if(err) return err;
return res;
});
// When above functions done call this func:
var arr3 = middleFunc(arr1, arr2, function(err, res){
if(err) return err;
return res;
});
// When above functions done call this func:
var arr4 = lastFuntion(arr3);
答案 0 :(得分:1)
目前的功能目前不是承诺。但是,它们遵循节点中的异步模式。
您可以使用promisify-node之类的东西,也可以自己动手:
// define the first 2 promises by calling firstFunc with inputs
var promise1 = new Promise(function resolver(resolve, reject) {
firstFunc(input1, function(err, res){
if(err) reject(err);
resolve(res);
});
var promise2 = new Promise(function resolver(resolve, reject) {
firstFunc(input2, function(err, res){
if(err) reject(err);
resolve(res);
});
// When promise1 & 2 resolve, execute the then handler
Promise.all([promise1, promise2]).then(function (arr) {
// Grab the resolved values
var arr1 = arr[0];
var arr2 = arr[1];
// return a new promise that is resolved when middleFunc completes
return new Promise(function resolver(resolve, reject) {
middleFunc(arr1, arr2, function(err, res){
if(err) reject(err);
resolve(res);
});
});
}).then(function (arr3) { // Execute this when middleFunc completes
return lastFuntion(arr3); // This function looks synchronous
}).catch(function (err) {
// Handle any errors along the way
});
编辑:如果您想更一般地创建promise1和promise2,请编写辅助函数:
// Helper function to construct a promise by calling firstFunc with input
var firstFuncHelper = function (input) {
return new Promise(function resolver(resolve, reject) {
firstFunc(input, function(err, res){
if(err) reject(err);
resolve(res);
});
};
var promise1 = firstFuncHelper(input1);
var promise2 = firstFuncHelper(input2);
// Rest of code above remains