简体   繁体   English

承诺和行动顺序

[英]Promises and Order of Operations

Apologies if this is a basic concept. 抱歉,这是一个基本概念。 I'm new to Javascript. 我是Java的新手。

I'm trying to understand the order of execution of the following functions. 我试图了解以下功能的执行顺序。 I setup a Promise with 2 callbacks and a Promise with 3 callbacks right after. 之后,我设置了一个带有2个回调的Promise和一个带有3个回调的Promise。

function getSum(n1, n2){
    var isAnyNegative = function() {
        return n1<0 || n2 < 0;
    }
    var promise = new Promise(function(resolve, reject) {
        if (isAnyNegative()){
            reject(Error('Negative not supported'));
        }
        resolve(n1 + n2)
    });
    return promise;
}

// Double Promise
getSum(5,6).then(function(result) {
  console.log('DL1 '+result);
  return getSum(10,20);
}, function(error){
  console.log(error);
}).then(function(result) {
  console.log('DL2 '+result);
}, function(error){
  console.log(error);
});

// Triple Promise
getSum(5,6).then(function(result) {
  console.log('TL1 '+result);
  return getSum(10,20);
}, function(error){
  console.log(error);
}).then(function(result){
  console.log('TL2 '+result);
  return getSum(30,40);
}, function(error){
  console.log(error);
}).then(function(result){
  console.log('TL3 ' +result);
}, function(error){
  console.log(error);
});

The output was as follows (DL=>Double Layer, TL=>Triple Layer): 输出如下(DL =>双层,TL =>三层):

DL1 11
TL1 11
DL2 30
TL2 30
TL3 70

It would have expected the output to be Double Layer then Triple Layer however that's not the case. 期望输出是双层然后是三层,但是事实并非如此。 I looked into Hoisting but what I've read about it, it should at least protect the order of execution within the script. 我研究了吊装,但据我了解,它至少应该保护脚本中的执行顺序。 How are these functions ordered and why are they not executed in order of appearance? 这些函数如何排序,为什么不按出现顺序执行?

If there's any more detail required please ask, Apologies and Thanks in Advance. 如果需要更多详细信息,请先向“道歉”和“谢谢”提出问题。

When running promises, each of the .then handlers run asynchronously as explained by https://javascript.info/microtask-queue 当运行Promise时,每个.then处理程序都会异步运行,如https://javascript.info/microtask-queue所述

Basically for your code it means 基本上对于您的代码来说,这意味着

  • The main code is run first, DL1 is queued, and TL1 is queued 首先运行主代码,DL1排队,TL1排队
  • As the execution of the main code ends, DL1 is first in queue so it executes and queues DL2 随着主代码执行的结束,DL1排在队列中的第一位,因此它执行并排入DL2
  • When the engine finishes with DL1, it takes the next queued item; 当引擎完成DL1时,它将接受下一个排队的项目。 TL1, which executes and queues TL2. TL1,它执行并排队TL2。
  • Now the next item in queue is DL2, and the remaining TLs follow 现在队列中的下一个项目是DL2,其余的TL紧随其后

If you really need the promises to resolve DLs first, then TLs, then you need to make them part of the same promise chain 如果您真的需要诺言先解决DL,然后再解决TL,则需要使它们成为同一诺言链的一部分

The order of execution from your example is correct. 您的示例中的执行顺序是正确的。

When it comes to asynchronous operations (Promises), the whole concept is a bit different with synchronous operations. 当涉及异步操作(Promises)时,整个概念与同步操作有所不同。

In the explanation below, you can assume Promise as if it is a schedule/queue to run operations. 在下面的说明中,您可以将Promise假定为运行操作的计划/队列。

Use this simplified code for example: 例如,使用以下简化代码:

 function sum(a, b){ return new Promise(function(resolve, reject){ if (a < 0 || b < 0) reject(new Error('Negative not supported.')); else resolve(a + b); }); } /* Double layer */ sum(5, 6).then(function(result){ console.log('DL1', result); return sum(10, 20); }).then(function(result){ console.log('DL2', result); }).catch(function(error){ console.error(error); }); /* Triple layer */ sum(5, 6).then(function(result){ console.log('TL1', result); return sum(10, 20); }).then(function(result){ console.log('TL2', result); return sum(30, 40); }).then(function(result){ console.log('TL3', result); }).catch(function(error){ console.error(error); }); 

If we follow the example above, the execution queue would look something like: 如果我们按照上面的示例,执行队列将类似于:

  1. Declare function sum . 声明函数sum
  2. Run function sum(5, 6) as DL. 将函数sum(5, 6)作为DL运行。
  3. Returns a Promise (DL), execution of sum (DL) ended. 返回一个Promise(DL), sum (DL)的执行结束。
  4. Run function sum(5, 6) as TL. 将函数sum(5, 6)作为TL运行。 Promise DL is running in background. Promise DL在后台运行。
  5. Returns a Promise (TL), execution of sum (TL) ended. 返回一个Promise(TL), sum (TL)的执行结束。 Promise DL is resolved in the background. Promise DL在后台解决。
  6. DL1 .then() is run because Promise DL was resolved in step 5. Promise TL is resolved in the background. 因为在步骤5中解决了Promise DL,所以运行了DL1 .then() 。在后台解决了Promise TL。
  7. TL1 .then() is run because Promise TL was resolved in step 6. DL1 is resolved in the background. 因为在步骤6中解决了Promise TL,所以运行TL1 .then() 。DL1在后台解决。
  8. DL2 .then() is run because Promise DL1 was resolved in step 7. Promise TL1 is resolved in the background. 因为在步骤7中已解决Promise DL1,所以运行了DL2 .then() 。在后台解决了Promise TL1。
  9. ... (you get the idea) ...(您知道了)

As you can see, with Promises, some operations were run in the background. 如您所见,使用Promises,一些操作在后台运行。 Which is why you will see the order of execution may not appear like how it is appeared. 这就是为什么您会看到执行顺序可能看起来不一样的原因。

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

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