简体   繁体   English

承诺中来自 Console.log() 的奇怪行为

[英]Weird Behavior from Console.log() in promises

so I'm doing some work with promises and getting some bizarre behavior when I use the console.log() in the promise.所以当我在 promise 中使用 console.log() 时,我正在做一些承诺工作并得到一些奇怪的行为。

CODE代码

function doSomething(msg){ 
      return new Promise(
        (myresolve, myreject) => {
          setTimeout(
             () => {
              console.log(msg);
              console.log('In the promise')
              myresolve();
            }, 
            1000);
        }); 
    }



   doSomething("1st Call")
  .then(function() {
    doSomething("2nd Call");
    console.log('leaving 2nd promise'); 
  })
  .then(function() {
    doSomething("3rd Call");
    console.log('leaving 3rd promise');
}); 

OUTPUT to CONSOLE OUTPUT 到控制台

  • '1st Call' '第一次通话'
  • 'In the promise' '在承诺中'
  • 'leaving 2nd promise' '留下第二个承诺'
  • 'leaving 3rd promise' '留下第三个承诺'
  • '2nd Call' “第二次通话”
  • 'In the promise' '在承诺中'
  • '3rd Call' “第三次通话”
  • 'In the promise' '在承诺中'

Main Question Why is it that JavaScript does not seem to read the lines of code in sequential order once in the promise?主要问题为什么 JavaScript 似乎没有按顺序读取 promise 中的代码行一次? It almost seems like it is making a pass first and console logging first, and then going back over the code and executing the functions that are promised to be executed after the.then method.几乎看起来它是先通过并首先进行控制台日志记录,然后返回代码并执行承诺在 .then 方法之后执行的函数。 Any insight would be greatly appreciated...任何见解将不胜感激......

doSomething("2nd Call");
console.log('leaving 2nd promise'); 

Do something is asynchronous and will take ~1000 m/s to finish its execution.做某事是异步的,需要~1000 m/s 才能完成它的执行。 So, when doSomething("2nd Call");所以,当doSomething("2nd Call"); is initially called, your code jumps into your method, returns the promise, and begins the setTimeout .最初调用时,您的代码跳转到您的方法,返回 promise,并开始setTimeout Then, "leaving 2nd promise" is logged.然后,记录"leaving 2nd promise" Later on down the track, the setTimeout that we initiated before by calling doSomething("2nd Call") will finish, and so it will log "2nd Call" to the console.稍后,我们之前通过调用doSomething("2nd Call")启动的 setTimeout 将完成,因此它将"2nd Call"记录到控制台。 To wait for your inital call to doSomething("2nd Call") to complete, you need to use .then() (or await ) on the promise it returns, such you can execute your code when the promise resolves:要等待您对doSomething("2nd Call")的初始调用完成,您需要在它返回的 promise 上使用 .then .then() (或await ),这样您就可以在 promise 解析时执行您的代码:

 function doSomething(msg) { return new Promise( (myresolve, myreject) => { setTimeout( () => { console.log(msg); console.log('In the promise') myresolve(); }, 1000); }); } doSomething("1st Call").then(() => doSomething("2nd Call")).then(() => console.log('leaving 2nd promise')).then(() => doSomething("3rd Call")).then(() => console.log('leaving 3rd promise'));

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

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