如何使用一系列promise来传递函数数组中的参数

时间:2017-09-23 01:29:07

标签: javascript promise es6-promise

我有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,但它不起作用。

任何想法???

1 个答案:

答案 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);
});