await與async的作用及用法

await與async的作用及用法

await與async的作用及用法

async和await被稱作是異步的終極解決方案

await有兩個作用,一是作爲求值關鍵字,二是將異步操作變成同步操作;如果方法中使用了await,那麼在方法前面必須加上async

  • 作爲求值關鍵字,await後面可以跟Promise或表達式,可以直接獲取Promise中的值或表達式的值

    • 後面跟Promise

      app.use(async (ctx, next) => {
        // next()返回的是Promise,a的值是"hello, world!"
        const a = await next();
        
        const b = next();
        b.then((res) => {
          console.log(res); // 打印出"hello, world!"
        })
      });
      
      app.use((ctx, next) => {
        return "hello, world!";
      })
      
    • 後面跟表達式

      const a = await 100*100;
      
  • 將異步操作變成同步操作

    await可以阻塞當前線程,將異步操作變成同步,被阻塞的線程並沒有被空閒,而是去執行其他的操作

async的作用是將方法的返回值封裝成Promise

async function t() {
  return "hello";
}

console.log(t()); // 打印出 Promise{"hello"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章