promise鏈
原來用promise的鏈式調(diào)用方式,then 中原本就返回了一個promise
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 3000); // (*)
}).then(function(result) { // (**)
console.log(result); // 1
return result * 2; // 將返回的promise狀態(tài)改為resolved
}).then(function(result) { // (***)
console.log(result); // 2
return result * 2;
}).then(function(result) {
console.log(result); // 4
return result * 2;
});
async
放在函數(shù)前面表示是異步函數(shù)悦析,異步函數(shù)也就意味著該函數(shù)的執(zhí)行不會阻塞后面代碼的執(zhí)行急灭。
函數(shù)前面的async一詞意味著一個簡單的事情:這個函數(shù)總是返回一個promise椭蹄,如果代碼中有return <非promise>語句衅檀,JavaScript會自動把返回的這個value值包裝成promise的resolved值灌闺,調(diào)用就像普通函數(shù)一樣調(diào)用呐粘,但是后面可以跟then()了
async function fn() {
return 1
}
fn().then(alert) // 1
也可以顯式的返回一個promise,這個將會是同樣的結(jié)果:
async function f() {
return Promise.resolve(1)
}
f().then(alert) // 1
async確保了函數(shù)返回一個promise蚂会,即使其中包含非promise淋样。
await
await只能在async函數(shù)里使用,它可以讓JavaScript進行等待胁住,直到一個promise執(zhí)行并返回它的結(jié)果趁猴,JavaScript才會繼續(xù)往下執(zhí)行。
await 可以用于等待的實際是一個返回值彪见,可是promise的返回值儡司,也可以是普通函數(shù)的返回值,或者使一個變量余指,注意到 await 不僅僅用于等 Promise 對象捕犬,它可以等任意表達式的結(jié)果跷坝,所以,await 后面實際是可以接普通函數(shù)調(diào)用或者直接變量的碉碉。
await不能在常規(guī)函數(shù)里使用await柴钻,不能工作在頂級作用域,只能在async函數(shù)中使用垢粮。
`定義一個await`
let value = await promise // value 可以得到promise成功后返回的結(jié)果, 然后才會繼續(xù)向下執(zhí)行
async function f() { // await 只能在async函數(shù)中使用
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 1000)
})
let result = await promise // 直到promise返回一個resolve值(*)才會執(zhí)行下一句
alert(result) // 'done!'
}
f()
function getSomething() {
return "something";
}
async function testAsync() {
return Promise.resolve("hello async");
}
const xxx = {a:1,b:2}
async function test() {
const v1 = await getSomething(); // await 后跟普通函數(shù)的返回值
const v2 = await testAsync(); // await 后跟異步函數(shù)的返回值
const v3 = await xxx
console.log(v1, v2,v3);
}
test();
一個class方法同樣能夠使用async贴届,只需要將async放在實例方法之前就可以,它確保了返回值是一個promise蜡吧,支持await毫蚓。如下:
class Waiter {
async wait () {
return await Promise.resolve(1)
}
}
new Waiter().wait().then(alert) // 1
await的異常處理
多個await連續(xù)時,會一個一個同步執(zhí)行昔善,如果中間有一個reject了元潘,就會停止后面的代碼執(zhí)行,所以需要用 try...catch處理錯誤
用try/catch 來捕獲異常君仆,把await 放到 try 中進行執(zhí)行翩概,如有異常,就使用catch 進行處理袖订。
async getFaceResult () {
try {
let location = await this.getLocation(this.phoneNum);
if (location.data.success) {
let province = location.data.obj.province;
let city = location.data.obj.city;
let result = await this.getFaceList(province, city);
if (result.data.success) {
this.faceList = result.data.obj;
}
}
} catch(err) {
console.log(err);
}
}
摘自:async和await