1. 程式人生 > 實用技巧 >js之async和await

js之async和await

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)。

以下摘自:Js中async/await的執行順序詳解

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:

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物件先推入佇列。