鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ Async / Await in IIFF ( 立即執(zhí)行函數(shù) )

Async / Await in IIFF ( 立即執(zhí)行函數(shù) )

預(yù)期以下代碼應(yīng)該打印順序會(huì)是 1 2 3 4 5 但實(shí)際執(zhí)行時(shí)卻是 1 2 5 3 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");

預(yù)計(jì) await new Promise 應(yīng)該是會(huì)等到 reslove("3"); 執(zhí)行后再順序執(zhí)行,怎麼就直接跳過了呢? 若是想要 1 2 3 4 5 的執(zhí)行該怎麼調(diào)整?

附注
.babelrc

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": ["transform-object-rest-spread"],
  "ignore": ["node_modules"]
}
回答
編輯回答
喵小咪

async/await是以同步的方式去寫異步代碼。你到2之后執(zhí)行的是setTimeout(),這是一個(gè)異步,后續(xù)的n和4都要等到resolve之后才能夠執(zhí)行。

setTimeout(() => {
    console.log(2)
}, 1000)
console.log(1)

執(zhí)行順序?yàn)? 2

和上面的是類似的,自執(zhí)行函數(shù)中,到了setTimeout()就是一個(gè)異步,后續(xù)都要等待resolve,自執(zhí)行函數(shù)“暫停了”,之后執(zhí)行的就是5了,然后等待resolve,輸出3,4

有錯(cuò)誤歡迎指出~共同學(xué)習(xí)

2018年2月9日 21:18
編輯回答
怪痞
(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");
})();
2017年3月20日 07:04
編輯回答
夕顏
(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");
});

代碼改成這樣你應(yīng)該就能理解了,因?yàn)?code>async function是一個(gè)Promise。雖然寫著await,但并不代表CPU就阻塞了。

2017年12月6日 06:51