async/await 是一種編寫異步代碼的新方法,之前異步代碼的方案是回調和 promise,但async/await建立在promise基礎上。
async和await是ES7中與異步操作有關的關鍵字。
async
async function name([param[, param[, ... param]]]) { statements }
async 函數返回一個 Promise 對象,可以使用 then 方法添加回調函數。如果在函數中 return 一個直接量,async 會把這個直接量通過 Promise.resolve()
封裝成 Promise 對象。
async function testAsync() { return "hello async"; } let result = testAsync(); console.log(result) // Promise {<resolved>: "hello async"}
await 關鍵字僅在 async function 中有效。如果在 async function 函數體外使用 await ,會得到一個語法錯誤。
await
[return_value] = await expression;
expression: 一個 Promise 對象或者任何要等待的值。
await針對所跟不同表達式的處理方式:
Promise對象:await 會暫停執行,等待 Promise 對象 resolve(異步操作完成),然后恢復 async 函數的執行並返回解析值。
非Promise對象:直接返回對應的值。
function testAwait (x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function helloAsync() { var x = await testAwait ("hello world"); console.log(x); } helloAsync (); // hello world
很多人以為await會一直等待之后的表達式執行完之后才會繼續執行后面的代碼,實際上await是一個讓出線程的標志。
await后面的函數會先執行一遍,然后就會跳出整個async函數來執行后面js棧(后面會詳述)的代碼。等本輪事件循環執行完了之后又會跳回到async函數中等待await后面表達式的返回值,
如果返回值為非promise則繼續執行async函數后面的代碼,否則將返回的promise放入promise隊列(Promise的Job Queue)。
function testSometing() { console.log("執行testSometing"); return "testSometing"; } async function testAsync() { console.log("執行testAsync"); return Promise.resolve("hello async"); } async function test() { console.log("test start..."); const v1 = await testSometing();//關鍵點1 console.log(v1); const v2 = await testAsync(); console.log(v2); console.log(v1, v2); } test(); var promise = new Promise((resolve)=> { console.log("promise start.."); resolve("promise");});//關鍵點2 promise.then((val)=> console.log(val)); console.log("test end...")
執行結果:
test start...
執行testSometing
promise start..
test end...
testSometing
執行testAsync
promise
hello async
testSometing hello async
在testSomething前增加aync:
async function testSometing() { console.log("執行testSometing"); return "testSometing"; } async function testAsync() { console.log("執行testAsync"); return Promise.resolve("hello async"); } async function test() { console.log("test start..."); const v1 = await testSometing();//關鍵點1 console.log(v1); const v2 = await testAsync(); console.log(v2); console.log(v1, v2); } test(); var promise = new Promise((resolve)=> { console.log("promise start.."); resolve("promise");});//關鍵點2 promise.then((val)=> console.log(val)); console.log("test end...") ///////////////////////////////////// test start... 執行testSometing promise start.. test end... promise testSometing 執行testAsync hello async testSometing hello async
和上一個例子比較發現promise.then((val)=> console.log(val));
先與console.log(v1);
執行了,原因是因為現在testSometing函數加了async,返回的是一個Promise對象要等它resolve,
所以將當前Promise推入隊列,所以會繼續跳出test函數執行后續代碼。之后就開始執行promise的任務隊列了,所以先執行了promise.then((val)=> console.log(val));
因為這個Promise對象先推入隊列。