JavaScript代碼在執(zhí)行的時(shí)候,可以說(shuō)就是拿一段代碼給到JavaScript引擎并去執(zhí)行忘分,此外還可能會(huì)提供額外的API給到JavaScript引擎。
在ES3 或者 更早的版本中,JavaScript并無(wú)異步操作,所以代碼給到JavaScript引擎栅螟,它就直接順次的執(zhí)行,這個(gè)任務(wù)是宿主發(fā)起的任務(wù)我們可以稱之為宏觀任務(wù)(macrotask)篱竭。
在ES5 或者 之后的版本力图,JavaScript出現(xiàn)了Promise,這就不需要瀏覽器的安排掺逼,引擎自己也可以發(fā)起任務(wù)吃媒,這個(gè)任務(wù)就叫做微觀任務(wù)(microtask)
Promise
MDN解釋:Promise 對(duì)象用于表示一個(gè)異步操作的最終狀態(tài)(完成或失敗),以及該異步操作的結(jié)果值晓折。
基本用法:
function sleep(duration) {
return new Promise(function(resolve, reject) {
setTimeout(resolve,duration);
})
}
sleep(1000)
.then( ()=> console.log("then"))
.catch( ()=> console.log('catch') )
.finally( () => console.log('finally'));
Promise.prototype.catch(onRejected)
添加一個(gè)拒絕(rejection) 回調(diào)到當(dāng)前 promise, 返回一個(gè)新的promise惑朦。當(dāng)這個(gè)回調(diào)函數(shù)被調(diào)用,新 promise 將以它的返回值來(lái)resolve漓概,否則如果當(dāng)前promise 進(jìn)入fulfilled狀態(tài),則以當(dāng)前promise的完成結(jié)果作為新promise的完成結(jié)果.
Promise.prototype.then(onFulfilled, onRejected)
添加解決(fulfillment)和拒絕(rejection)回調(diào)到當(dāng)前 promise, 返回一個(gè)新的 promise, 將以回調(diào)的返回值來(lái)resolve.
Promise.prototype.finally(onFinally)
添加一個(gè)事件處理回調(diào)于當(dāng)前promise對(duì)象病梢,并且在原promise對(duì)象解析完畢后胃珍,返回一個(gè)新的promise對(duì)象◎涯埃回調(diào)會(huì)在當(dāng)前promise運(yùn)行完畢后被調(diào)用觅彰,無(wú)論當(dāng)前promise的狀態(tài)是完成(fulfilled)還是失敗(rejected)
function sleep(duration) {
return new Promise(function(resolve, reject) {
console.log("b");
setTimeout(resolve,duration);
})
}
console.log("a");
sleep(5000).then(()=>console.log("c"));
setTimeout 是屬于宿主環(huán)境的api,屬于宏觀任務(wù)钮热,所以可以分析為兩個(gè)宏觀任務(wù)填抬,但是setTimeout中帶有一個(gè)微觀任務(wù)。所以執(zhí)行結(jié)果為a b c
async/await
當(dāng)調(diào)用一個(gè) async
函數(shù)時(shí)隧期,會(huì)返回一個(gè) Promise
對(duì)象飒责。當(dāng)這個(gè) async
函數(shù)返回一個(gè)值時(shí),Promise
的 resolve 方法會(huì)負(fù)責(zé)傳遞這個(gè)值仆潮;當(dāng) async
函數(shù)拋出異常時(shí)宏蛉,Promise
的 reject 方法也會(huì)傳遞這個(gè)異常值。
async
函數(shù)中可能會(huì)有 await
表達(dá)式性置,這會(huì)使 async
函數(shù)暫停執(zhí)行拾并,等待 Promise
的結(jié)果出來(lái),然后恢復(fù)async
函數(shù)的執(zhí)行并返回解析值(resolved)鹏浅。
注意嗅义, await
關(guān)鍵字僅僅在 async
function中有效。如果在 async function
函數(shù)體外使用 await
隐砸,你只會(huì)得到一個(gè)語(yǔ)法錯(cuò)誤(對(duì)象代表嘗試解析語(yǔ)法上不合法的代碼的錯(cuò)誤之碗。)。
var resolveAfter2Seconds = function() {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("slow");
console.log("slow promise is done");
}, 2000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("fast");
console.log("fast promise is done");
}, 1000);
});
};
var sequentialStart = async function() {
console.log('==SEQUENTIAL START==');
// 1. Execution gets here almost instantly
const slow = await resolveAfter2Seconds();
console.log(slow); // 2. this runs 2 seconds after 1.
const fast = await resolveAfter1Second();
console.log(fast); // 3. this runs 3 seconds after 1.
}
var concurrentStart = async function() {
console.log('==CONCURRENT START with await==');
const slow = resolveAfter2Seconds(); // starts timer immediately
const fast = resolveAfter1Second(); // starts timer immediately
// 1. Execution gets here almost instantly
console.log(await slow); // 2. this runs 2 seconds after 1.
console.log(await fast); // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}
var concurrentPromise = function() {
console.log('==CONCURRENT START with Promise.all==');
return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
console.log(messages[0]); // slow
console.log(messages[1]); // fast
});
}
var parallel = async function() {
console.log('==PARALLEL with await Promise.all==');
// Start 2 "jobs" in parallel and wait for both of them to complete
await Promise.all([
(async()=>console.log(await resolveAfter2Seconds()))(),
(async()=>console.log(await resolveAfter1Second()))()
]);
}
// This function does not handle errors. See warning below!
var parallelPromise = function() {
console.log('==PARALLEL with Promise.then==');
resolveAfter2Seconds().then((message)=>console.log(message));
resolveAfter1Second().then((message)=>console.log(message));
}
sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(concurrentPromise, 7000); // same as concurrentStart
// wait again
setTimeout(parallel, 10000); // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
// wait again
setTimeout(parallelPromise, 13000); // same as parallel