Async / Await in IIFF (execute the function immediately)

it is expected that the following code should be printed in the order of 1 2 3 4 5, but when it is actually executed, it is 1 2 5 3 4 4

(async () => {
  console.log("1");
  let n = await new Promise((reslove, reject) => {
    console.log("2");
    setTimeout(() => {
      reslove("3");
    }, 2000);
  });
  console.log(n);
  console.log("4");
})();

console.log("5");

it is expected that await new Promise will wait until reslove ("3"). If it is executed sequentially, how can it be skipped directly? How to adjust if you want to implement 1 2 3 4 5?

Note
.babelrc

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": ["transform-object-rest-spread"],
  "ignore": ["node_modules"]
}
Mar.03,2021

setTimeout is a macrotask, so 1.25 will be output first, and resolve 3 will not go out until the next event loop, setTimeout , and then log 4



(async() => {
    console.log("1");
    let n = await new Promise((reslove, reject) => {
        console.log("2");
        setTimeout(() => {
            reslove("3");
        }, 2000);
    });
    console.log(n);
    console.log("4");
})().then(()=>{
    console.log("5");
});
You should be able to understand the

code so that you can understand it, because async function is a Promise . Although it says await , it doesn't mean that CPU is blocked.

Menu