A problem about Serial promise

now use a code like this:

(() => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("task1 -> 3s")
      resolve()
    }, 3000);
  })
  .then(() => {
      setTimeout(() => {
        console.log("task2 -> 2s")
        Promise.resolve()
      }, 2000);
  })
  .then(() => {
    setTimeout(() => {
      console.log("task3 -> 1s")
    }, 1000);
  })
})()
 task1 -> task3 -> task2

if you change it to:

(() => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("task1 -> 3s")
      resolve()
    }, 3000);
  })
  .then(() => {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("task2 -> 2s")
        resolve()
      }, 2000);
    })
  })
  .then(() => {
    setTimeout(() => {
      console.log("task3 -> 1s")
    }, 1000);
  })
})()

is fine
, but if you change the second then to return another promise, it will be no problem. I would like to ask why, my idea is, the first way to use Promise.then () is not to wait for this asynchronous function to finish execution before executing the following?

Please tell me what is wrong. Thank you ~

Jul.05,2022

the callback function of the second then has no input and no return value, where setTimeout is completely independent and has nothing to do with the outer then chain.

in addition, Promise.resovle () in setTimeout () produces a Promise object of resolved, but this object is not returned or used, so it has nothing to do with other code

.

since it doesn't matter, it certainly won't play a role in the process.

Note: (resolve, reject) = > {} resolve () and Promise.resolve () are slightly different in the code.


Why:
the function received by then will be judged,
if the function is promise, then the next then will become the then of the incoming promise,
if the function is not promise, then the next then is the then of the original promise

Menu