简体   繁体   中英

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.

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

  • '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? 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. 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. So, when doSomething("2nd Call"); is initially called, your code jumps into your method, returns the promise, and begins the setTimeout . Then, "leaving 2nd promise" is logged. 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. 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:

 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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