JavaScript承诺:顺序执行承诺 [英] JavaScript Promises: Executing Promises Sequentially

查看:76
本文介绍了JavaScript承诺:顺序执行承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更清楚地理解诺言,我一直在阅读一些关于它的非常有趣的文章。我遇到了以下代码,这些代码非常适合顺序执行promise。但是我不明白它是如何工作的。

In an attempt to understand promises more clearly, i have been reading up a few very interesting articles on the same. I came across the following code which works perfectly for executing promises sequentially. But i am not able to understand how it works.

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

 function doSecondThing(res){
   return new Promise(function(resolve,reject){
       setTimeout(()=>{
           resolve(res + 1);
       },1000)
   })
 }

 function doThirdThing(res){
   return new Promise(function(resolve,reject){
       setTimeout(()=>{
           resolve(res + 2);
       },1000)
   })
 }
 promiseFactories = [doFirstThing, doSecondThing, doThirdThing];

 function executeSequentially(promiseFactories) {
         var result = Promise.resolve(); // this is the most problematic line 
               promiseFactories.forEach(function (promiseFactory) {
               result = result.then(promiseFactory);// what is happening here ?
    });
    return result;
 }

 executeSequentially(promiseFactories)

我确实知道承诺一经创建便立即执行。由于某种原因,我无法理解执行流程。特别是以下行:

I do understand that promises are executed as soon as they are created. For some reason i am not able to understand the flow of execution. Especially this following line:

var result = Promise.resolve()//and empty promise is created.

请有人帮助我了解如何在空的'then'方法内调用promiseFactory方法promise使它按顺序执行,就像这样。还是因为forEach循环?

Please if somebody can help me understand how calling the promiseFactory method inside the 'then' method of the empty promise makes it execute sequentially, like so. Or is it because of the forEach loop ?

result = result.then(promiseFactory);

我尝试用地图功能替换 forEach,但仍然产生了相同的结果。即按顺序执行的方法。
另外,值如何从一个链接的函数传递给其他函数?

I tried replacing the 'forEach' with a 'map' function and still yielded the same result. i.e, the methods where executed sequentially. Also, how is the value passed from one chained function to other ?

任何帮助或文章/博客都受到高度赞赏。

Any help or article/blog is highly appreciated.

推荐答案

executeSequentially 方法一个接一个地返回所有Promises。它碰巧遍历了 promiseFactory ,但是它可以写​​为:

The executeSequentially method returns all the Promises one after each other. It happens to iterate over promiseFactory, but it could be written as:

function executeSequentially(promiseFactories) {
  return doFirstThing()
  .then(() => doSecondThing())
  .then(doThirdThing() );
}

这是相同的。

现在,我们要重申一系列承诺。

Now, however, we want to iterate over a collection of promises.

迭代时,我们需要在当前Promise之前附加一个 then 。但是 forEach 不会在每次迭代中公开下一个Promise或上一个Promise。但是,我们仍然需要它来保持Promises一对一的链接。因此, result 'hack':

When iterating, we need to attach the current Promise to the previous with a then. But the forEach does not expose the next Promise -or the previous- in every iteration. And yet we still need it in order to keep chaining Promises one by one. Hence, the result 'hack':

function executeSequentially(promiseFactories) {
  var result = Promise.resolve(); /*We need a thing that keeps yelling 
  the previous promise in every iteration, so we can keep chaining.
  This 'result' var is that thing. This is keeping a Promise in every
  iteration that resolves when all the previous promises resolve
  sequentially. Since we don't have a Promise in the array
  previous to the first one, we fabricate one out of 'thin air'
  with Promise.resolve() */
  promiseFactories.forEach(function (promiseFactory) {
    result = result.then(promiseFactory); /* Here result is update
    with a new Promise, with is the result of  chaining `result`
    with the current one. Since `result` already had all the previous ones,
    at the end, `result` will be a Promise that depends upon all the
    Promises resolution.*/
  });
return result;
}

现在,还有一个语法怪癖可能使您感到困惑:

Now, there's also a syntax quirk that maybe is puzzling you:

result = result.then(promiseFactory);

此行与以下内容大致相同:

This line is pretty much the same as the following:

result = result.then(resolvedValue => promiseFactory(resolvedValue));




请有人帮助我了解如何在内部调用promiseFactory方法空承诺的'then'方法使它依次执行,就像这样。还是因为forEach循环?

Please if somebody can help me understand how calling the promiseFactory method inside the 'then' method of the empty promise makes it execute sequentially, like so. Or is it because of the forEach loop ?

首先, promiseFactory 那是一个很坏的名字。该方法应更好地编写如下:

First thing first, promiseFactory is a pretty bad name there. The method should be better written as follows:

function executeSequentially(promises) {
  var result = Promise.resolve(); // this is the most problematic line 
        promises.forEach(function (currentPromise) {
        result = result.then(currentPromise);// what is happening here ?
});
return result;
}

因此:


如何在空承诺的'then'方法内调用 currentPromise 方法使其依次执行?

它使顺序执行,因为当您通过然后将一个Promise附加到另一个时,它会顺序执行。是然后的事情,它与我们遍历Promises的事实完全无关。在迭代之外使用普通的Promises,它的工作原理几乎相同:

It makes execute sequentially because when you attach a Promise to another by then, it executes sequentially. Is a then thing, it is not at all related to the fact that we are iterating over Promises. With plain Promises outside an iteration it works pretty much the same:

Promise.resolve() // fake Promises that resolves instanly
.then(fetchUsersFromDatabase) // a function that returns a Promise and takes
// like 1 second. It won't be called until the first one resolves
.then(processUsersData) // another function that takes input from the first, and
// do a lot of complex and asynchronous computations with data from the previous promise.
// it won't be called until `fetchUsersFromDatabase()` resolves, that's what
// `then()` does.
.then(sendDataToClient); // another function that will never be called until
// `processUsersData()` resolves

这篇关于JavaScript承诺:顺序执行承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆