我有Promises的以下功能:
const func1 = () => new Promise((resolve, reject) => {
console.log('func1 start');
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = (param_from_func1) => new Promise((resolve, reject) => {
console.log('func2 start ' + param_from_func1); // Want to get the value 'Hello' here
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
为了执行这些函数,我使用:
const Promise = require('bluebird');
Promise.series = (promiseArr) => {
return Promise.reduce(promiseArr, (values, promise) => {
return promise().then((result) => {
values.push(result); // And here, I don't know how I can modify this to pass parameters between functions
return values;
});
}, []);
};
致电:
Promise.series([func1, func2]).then(values => {
console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
console.log("Promise Rejected. " + reason);
});
一切正常,因为我可以根据函数的顺序排列一系列值。
所以,我有两个问题:
如何将参数从func1
传递到func2
?
如何将参数从func1
传递给func2
,从.find
传递?
答案 0 :(得分:2)
如果要传递先前的结果,则只需将values
数组传播到promise-returning函数。替换:
promise().then
使用:
promise(...values).then
const func1 = () => new Promise((resolve, reject) => {
console.log('func1 start');
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = (param_from_func1) => new Promise((resolve, reject) => {
console.log('func2 start ' + param_from_func1); // Want to get the value 'Hello' here
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
Promise.series = (promiseArr) => {
return Promise.reduce(promiseArr, (values, promise) => {
return promise(...values).then((result) => {
values.push(result); // And here, I don't know how I can modify this to pass parameters between functions
return values;
});
}, []);
};
Promise.series([func1, func2]).then(values => {
console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
console.log("Promise Rejected. " + reason);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
&#13;
[spread syntax
]用不同的参数替换数组,就像你单独列出它们一样。请参阅spread syntax for function calls。
如果您还要将值传递给第一个函数,则可以在传递给reduce
方法的初始值中指定它。那么请替换:
, []);
使用:
, [some_value]);
请注意,此值也将传递给第二个函数,然后第二个函数将接收两个参数而不是一个参数。如果您希望每个函数只接收一个值,即前一个承诺返回的值,而不是之前的所有承诺,则替换
promise(...values)
与
promise(values[values.length-1]).
这样他们都只传递了一个值。