我有Promises的以下功能:
const func1 = () => new Promise((resolve, reject) => {
console.log('func1 start');
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = () => new Promise((resolve, reject) => {
console.log('func2 start');
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
为了执行这些函数,我使用:
const promiseSerial = funcs =>
funcs.reduce((promise, func) =>
promise.then(result => func().then(Array.prototype.concat.bind(result))),
Promise.resolve([]))
致电:
promiseSerial([func1, func2]).then(values => {
console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
console.log("Promise Rejected. " + reason);
});
一切正常,因为我可以根据函数的顺序排列一系列值。
所以,我的问题是:
如何在函数之间传递参数?我的意思是,我想将参数从func1
传递给func2
。我想过可能在resolve
,但它不起作用。
任何想法???
答案 0 :(得分:1)
在func2()
替换
const func2 = ()
到
const func2 = (PARAMETER)
在promiseSerial()
替换
promise.then(result => func()
到
promise.then(result => func(result[0])
console.log
func2中的PARAMETER
会显示字符串'Hello'
要将参数发送到func1
,如果您有多个funcs
const func1 = (FIRST_PARA) => new Promise((resolve, reject) => {
console.log('func1 start, the first parameter is ' + FIRST_PARA);
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = (FIRST_PARA, LAST_PARA) => new Promise((resolve, reject) => {
console.log('func2 start, the received last parameter is ' + LAST_PARA);
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
const promiseSerial = (funcs, firstParameter) => funcs.reduce((promise, func) =>
promise.then(result => func(firstParameter, result[result.length - 1]).then(Array.prototype.concat.bind(result))), Promise.resolve([]))
var firstParameter = 12;
promiseSerial([func1, func2], firstParameter).then(values => {
console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
console.log("Promise Rejected. " + reason);
});