Promise execution order

console.log("main-1")

function foo(param){
  var p = new Promise(function(resolve, reject) {
    console.log("promise-1")

    if (param === 1) {
      resolve("1")
    } else {
      reject("2")
    }

    console.log("promise-2")
  })

  return p
}

console.log("main-2")

foo(1).then(function(value) {
  console.log("then-1")
})

console.log("main-3")

the running result is main-1
main-2
promise-1
promise-2
main-3
then-1

Why does main-3 run after promise

Aug.02,2021

promise async refers to the then () method, not its constructor execution. For more information, please see Promise

.

it is suggested that the landlord read this article carefully to learn more about the event mechanism in JavaScript

.

Promise is created and executed, which can be thought of as Synchronize execution.


because Promise belongs to Synchronize except resolve and reject. That is to say, the order of execution in Promise is
* * first console.log ('promise-1');
* * then encounters resolve, asynchronous, skipping waiting for execution.
* * then Synchronize executes further so that it encounters console.log ('promise-2') and executes.
* * the code for ok Synchronize is finished, and the Promise is over.
* * then execute, console.log ('main-3'), and after executing this console, the code of ok Synchronize is finished.
* * executes the asynchronous code in Promise, that is, resolve,console.log ('then-1');
asynchronous code waits for a period of time before it executes. At the same time, Synchronize code does not stop execution, it will go all the way down


Promise constructor is the, resolve () / reject () that Synchronize executes. The function in Promise.then () is executed asynchronously

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9d213-476e9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9d213-476e9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?