[英]Call same function multiple times with different parameters. When done: Use each return value in other function
Does anyone have an idea how to make a plausible promise chain for this asynchronous JavaScript code: 有谁知道如何为该异步JavaScript代码制作合理的Promise链:
Updated: 更新:
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);
The functions as they stand are not currently promises. 这些功能目前尚不能保证。 They do, however, follow the async pattern in node.
但是,它们确实遵循节点中的异步模式。
You can either use something like promisify-node or do it yourself: 您可以使用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
});
Edit : If you want to create promise1 and promise2 more generically, write a helper function: 编辑 :如果要更一般地创建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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.