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

时间:2017-09-26 00:05:08

标签: javascript promise bluebird

我有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);
});

一切正常,因为我可以根据函数的顺序排列一系列值。

所以,我有两个问题:

  1. 如何将参数从func1传递到func2

  2. 如何将参数从func1传递给func2,从.find传递?

1 个答案:

答案 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;
&#13;
&#13;

[spread syntax]用不同的参数替换数组,就像你单独列出它们一样。请参阅spread syntax for function calls

如果您还要将值传递给第一个函数,则可以在传递给reduce方法的初始值中指定它。那么请替换:

, []);

使用:

, [some_value]);

请注意,此值也将传递给第二个函数,然后第二个函数将接收两个参数而不是一个参数。如果您希望每个函数只接收一个值,即前一个承诺返回的值,而不是之前的所有承诺,则替换

promise(...values)

promise(values[values.length-1]). 

这样他们都只传递了一个值。