新聞中心
async 作為一個(gè)關(guān)鍵字放到函數(shù)前面,用于表示函數(shù)是一個(gè)異步函數(shù),因?yàn)閍sync就是異步的意思, 異步函數(shù)也就意味著該函數(shù)的執(zhí)行不會(huì)阻塞后面代碼的執(zhí)行。

async
語(yǔ)法
async function name([param[, param[, ... param]]]) { statements }
-
name: 函數(shù)名稱。
-
param: 要傳遞給函數(shù)的參數(shù)的名稱。
-
statements: 函數(shù)體語(yǔ)句。
返回值
async 函數(shù)返回一個(gè) Promise 對(duì)象,可以使用 then 方法添加回調(diào)函數(shù)。
async function helloAsync(){
return "helloAsync";
}
console.log(helloAsync()) // Promise {: "helloAsync"}
helloAsync().then(v=>{
console.log(v); // helloAsync
})
async 函數(shù)中可能會(huì)有 await 表達(dá)式,async 函數(shù)執(zhí)行時(shí),如果遇到 await 就會(huì)先暫停執(zhí)行 ,等到觸發(fā)的異步操作完成后,恢復(fù) async 函數(shù)的執(zhí)行并返回解析值。
await 關(guān)鍵字僅在 async function 中有效。如果在 async function 函數(shù)體外使用 await ,你只會(huì)得到一個(gè)語(yǔ)法錯(cuò)誤。
function testAwait(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait");
resolve();
}, 1000);
});
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync
await
await 操作符用于等待一個(gè) Promise 對(duì)象, 它只能在異步函數(shù) async function 內(nèi)部使用。
語(yǔ)法
[return_value] = await expression;
expression: 一個(gè) Promise 對(duì)象或者任何要等待的值。
返回值
返回 Promise 對(duì)象的處理結(jié)果。如果等待的不是 Promise 對(duì)象,則返回該值本身。
如果一個(gè) Promise 被傳遞給一個(gè) await 操作符,await 將等待 Promise 正常處理完成并返回其處理結(jié)果。
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 命令后面是一個(gè) Promise 對(duì)象,它也可以跟其他值,如字符串,布爾值,數(shù)值以及普通函數(shù)。
function testAwait(){
console.log("testAwait");
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync
await針對(duì)所跟不同表達(dá)式的處理方式:
Promise 對(duì)象:await 會(huì)暫停執(zhí)行,等待 Promise 對(duì)象 resolve,然后恢復(fù) async 函數(shù)的執(zhí)行并返回解析值。 非 Promise 對(duì)象:直接返回對(duì)應(yīng)的值。
網(wǎng)站欄目:講解一下ES6async關(guān)鍵字的使用方法
鏈接地址:http://m.fisionsoft.com.cn/article/ccogocp.html


咨詢
建站咨詢
