简体   繁体   English

如何使用可变函数调用创建顺序promise循环

[英]How to create a sequential promise loop with variable function calls

I need to somehow loop over the work array passed to _start then for each of the items in the array, I need to somehow call the corresponding function with the same name. 我需要以某种方式循环传递给_startwork数组然后对于数组中的每个项目,我需要以某种方式调用具有相同名称的相应函数。

I don't have control over the number of items in work the array or the number of items, I do know that there will always be a corresponding function. 我无法控制work的项目数量或项目数量,我知道总会有相应的功能。

I don't want to call all the functions at the same time, once the first function resolves after 3 seconds, I then want to call the second function, once the second function resolves after 3 seconds I then want to call the third function. 我不想同时调用所有函数,一旦第一个函数在3秒后解析,我就想调用第二个函数,一旦第二个函数在3秒后解析,我就想调用第三个函数。 Once the third function resolves after another 3 seconds I want to call _done(). 一旦第三个函数在另外3秒后解析,我想调用_done()。

In this example each function takes 3 seconds to complete _done wont gete called for 9 seconds. 在这个例子中,每个函数需要3秒才能完成_done不会被调用9秒。

function _start(data){
    // Insert some kinda native magic loop
}


function _one(){
    return new Promise((resolve, reject) => {
        setTimeout(function(){ 
            resolve(1); 
        }, 3000);
    })
};


function _two(){
    return new Promise((resolve, reject) => {
        setTimeout(function(){ 
            resolve(2); 
        }, 3000);
    })
};

function _done(){
    console.log('All done in 9 seconds)
}


(function(){
    var work = ['_one', '_two', '_two'];
    _start(work);
})();

Given the order is dicated by the array, you can use reduce to aggregate the promises into a chain 鉴于顺序由数组指定,您可以使用reduce将promises聚合到一个链中

const _start = (...actions) => {
  return actions.reduce((chain, action) => {
    const func = this[action];
    return chain.then(() => func());
  }, Promise.resolve());
}
...
_start('_one', '_two', '_three').then(() => console.log('All done'));

See it in action - the example appends an extra then to the chain just to output any results from the promises (probably outwith the scope of this question but something you may have to consider if getting data back is required). 看到它在行动 -例子追加额外then到链只是为了输出的承诺的任何结果(可能outwith这个问题的范围,但你可能有,如果让数据传回需要考虑的东西)。

Update 更新

Can see you intend on invoking _start from a different context in which the functions are declared, this is fine but you need to make sure you set the correct context before hand ie 可以看到你打算从声明_start的不同上下文中调用_start ,这很好,但是你需要确保在手之前设置正确的上下文,即

const self = this;
(function() {
  _start.bind(self)('_one', '_two', '_two');
})();

A function which creates a promise which sleeps: 一个创造睡眠承诺的功能:

const sleep = n => () => new Promise(resolve => setTimeout(resolve, n));

A function which sleeps after some input promise: 一些输入承诺后休眠的函数:

const sleepAfter = n => p => p.then(sleep(n));

A function which chains a bunch of promises, represented by functions: 链接一堆承诺的函数,由函数表示:

const chain = (...promises) => promises.reduce((ret, promise) => ret.then(promise), 
  Promise.resolve());

Run a bunch of functions yielding promises, sleeping in between: 运行一堆函数产生承诺,睡在两者之间:

const _start = promises => chain(promises.map(sleepAfter(3000)));

Now just: 现在只是:

_start(_one, _two, _three).then(_done);

Try using this: 试试这个:

_one().then((firstResponse) {
      return_two();
}) .then((secondResponse) => {
 *second and first respone are already done*

});

Use promises then then使用promises

_one().then((responseOne) => {
    return _two();
}).then((responseTwo) => {
    // _one & _two are done
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM