摘要:對象代表一個異步操作,有三種狀態(tài)進行中已成功和已失敗。這時,前一個回調(diào)函數(shù),有可能返回的還是一個對象即有異步操作,這時后一個回調(diào)函數(shù),就會等待該對象的狀態(tài)發(fā)生變化,才會被調(diào)用。
Promise 的含義
基本用法
Promise.prototype.then()
Promise.prototype.catch()
Promise.prototype.finally()
Promise.all()
Promise.race()
Promise.resolve()
Promise.reject()
應(yīng)用
Promise.try()
1.Promise 的含義
Promise,簡單說就是一個容器,里面保存著某個未來才會結(jié)束的事件(通常是一個異步reject resolve)
1.1特點
1.1.1對象的狀態(tài)不受外界影響。Promise對象代表一個異步操作,有三種狀態(tài):pending(進行中)、fulfilled(已成功)和rejected(已失敗。
只有異步操作的結(jié)果,可以決定當(dāng)前是哪一種狀態(tài),任何其他操作都無法改變這個狀態(tài)。
1.1.2一旦狀態(tài)改變,就不會再變,任何時候都可以得到這個結(jié)果。
Promise對象的狀態(tài)改變,只有兩種可能:從pending變?yōu)閒ulfilled和從pending變?yōu)閞ejected。
如果改變已經(jīng)發(fā)生了,你再對Promise對象添加回調(diào)函數(shù)(then,reject,resolved),也會立即得到這個結(jié)果。這與事件(Event)完全不同,事件的特點是,如果你錯過了它,再去監(jiān)聽,是得不到結(jié)果的。
1.2缺點
1.2.1一旦新建,立刻執(zhí)行,不能中斷。
1.2.2如果不設(shè)置回調(diào)函數(shù),Promise內(nèi)部拋出的錯誤,不會反應(yīng)到外部
1.2.3當(dāng)處于pending狀態(tài)時,無法得知目前進展到哪一個階段(剛剛開始還是即將完成
2.基本用法
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/ 異步操作成功 /){
resolve(value);
} else {
reject(error);
}
});
Promise構(gòu)造函數(shù)接受一個函數(shù)作為參數(shù),該函數(shù)的兩個參數(shù)分別是resolve和reject。它們是兩個函數(shù)。(兩個函數(shù)的調(diào)用都放在本輪事件的末尾)
2.1resolved函數(shù)作用
把狀態(tài)變?yōu)槌晒?,在異步操作成功后用,參?shù)為異步操作的結(jié)果
2.2rejected函數(shù)作用
把狀態(tài)變?yōu)槭?,在異步失敗后用,參?shù)為拋出的錯誤。
2.3Promise實例生成以后(狀態(tài)會變,成功或者失敗。然后調(diào)用then里得方法),可以用then方法分別指定resolved狀態(tài)和rejected狀態(tài)的回調(diào)函數(shù)。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
例子:
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, "done");
});
}
timeout(100).then((value) => {
console.log(value);
});
上面代碼中,timeout方法返回一個Promise實例,表示一段時間以后才會發(fā)生的結(jié)果。過了指定的時間(ms參數(shù))以后,Promise實例的狀態(tài)變?yōu)閞esolved,就會觸發(fā)then方法綁定的回調(diào)函數(shù)
2.4Promise 新建后就會立即執(zhí)行。
let promise = new Promise(function(resolve, reject) {
console.log("Promise");
resolve();
});
promise.then(function() {
console.log("resolved.");
});
console.log("Hi!");
// Promise
// Hi!
// resolved
上面代碼中,Promise 新建后立即執(zhí)行,所以首先輸出的是Promise。然后,then方法指定的回調(diào)函數(shù),將在當(dāng)前腳本所有同步任務(wù)執(zhí)行完才會執(zhí)行,所以resolved最后輸出。
2.5異步加載圖片的例子。
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
const image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error("Could not load image at " + url)); }; image.src = url;
});
}
上面代碼中,使用Promise包裝了一個圖片加載的異步操作。如果加載成功,就調(diào)用resolve方法,否則就調(diào)用reject方法
const getJSON = function(url) {
const promise = new Promise(function(resolve, reject){
const handler = function() { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send();
});
return promise;
};
getJSON("/posts.json").then(function(json) {
console.log("Contents: " + json);
}, function(error) {
console.error("出錯了", error);
});
上面代碼中,getJSON是對 XMLHttpRequest 對象的封裝,用于發(fā)出一個針對 JSON 數(shù)據(jù)的 HTTP 請求,并且
返回一個Promise對象。
需要注意的是,在getJSON內(nèi)部,resolve函數(shù)和reject函數(shù)調(diào)用時,都帶有參數(shù)。
如果調(diào)用resolve函數(shù)和reject函數(shù)時帶有參數(shù),那么它們的參數(shù)會被傳遞給回調(diào)函數(shù)。reject函數(shù)的參數(shù)通常是Error對象的實例,表示拋出的錯誤;
2.6 resolve函數(shù)的參數(shù)除了正常的值以外,還可能是另一個 Promise 實例,比如像下面這樣。
const p1 = new Promise(function (resolve, reject) {
// ...
});
const p2 = new Promise(function (resolve, reject) {
// ...
resolve(p1);
})
上面代碼中,p1和p2都是 Promise 的實例,但是p2的resolve方法將p1作為參數(shù),即一個異步操作的結(jié)果是返回另一個異步操作。
注意,這時p1的狀態(tài)就會傳遞給p2,也就是說,p1的狀態(tài)決定了p2的狀態(tài)。如果p1的狀態(tài)是pending,那么p2的回調(diào)函數(shù)就會等待p1的狀態(tài)改變;如果p1的狀態(tài)已經(jīng)是resolved或者rejected,那么p2的回調(diào)函數(shù)將會立刻執(zhí)行。
const p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error("fail")), 3000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => resolve(p1), 1000)
})
p2
.then(result => console.log(result))
.catch(error => console.log(error))
// Error: fail
上面代碼中,p1是一個 Promise,3 秒之后變?yōu)閞ejected。p2的狀態(tài)在 1 秒之后改變,resolve方法返回的是p1。由于p2返回的是另一個 Promise,導(dǎo)致p2自己的狀態(tài)無效了,由p1的狀態(tài)決定p2的狀態(tài)。所以,后面的then語句都變成針對后者(p1)。又過了 2 秒,p1變?yōu)閞ejected,導(dǎo)致觸發(fā)catch方法指定的回調(diào)函數(shù)。
2.7注意,調(diào)用resolve或reject并不會終結(jié) Promise 的參數(shù)函數(shù)的執(zhí)行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
上面代碼中,調(diào)用resolve(1)以后,后面的console.log(2)還是會執(zhí)行,并且會首先打印出來。這是因為立即 resolved 的 Promise 是在本輪事件循環(huán)的末尾執(zhí)行,總是晚于本輪循環(huán)的同步任務(wù)。
2.8調(diào)用resolve或reject以后,Promise 的使命就完成了,后繼操作應(yīng)該放到then方法里面,而不應(yīng)該直接寫在resolve或reject的后面。所以,最好在它們前面加上return語句,這樣就不會有意外。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的語句不會執(zhí)行
console.log(2);
})
3.Promise.prototype.then()
Then接收判斷上一個then返回的新實例再是成功還是失敗來調(diào)用函數(shù)
它的作用是為 Promise 實例添加狀態(tài)改變時的回調(diào)函數(shù)。
then方法的第一個參數(shù)是resolved狀態(tài)的回調(diào)函數(shù),第二個參數(shù)(可選)是rejected狀態(tài)的回調(diào)函數(shù)
3.1then方法返回的是一個新的Promise實例(注意,不是原來那個Promise實例)。因此可以采用鏈?zhǔn)綄懛?,即then方法后面再調(diào)用另一個then方法
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
上面的代碼使用then方法,依次指定了兩個回調(diào)函數(shù)。第一個回調(diào)函數(shù)完成以后,會將返回結(jié)果作為參數(shù),傳入第二個回調(diào)函數(shù)。
3.2采用鏈?zhǔn)降膖hen,可以指定一組按照次序調(diào)用的回調(diào)函數(shù)。這時,前一個回調(diào)函數(shù),有可能返回的還是一個Promise對象(即有異步操作),這時后一個回調(diào)函數(shù),就會等待該Promise對象的狀態(tài)發(fā)生變化,才會被調(diào)用。
4.Promise.prototype.catch()
4.1Promise.prototype.catch方法是.then(null, rejection)或.then(undefined, rejection)的別名,用于指定發(fā)生錯誤時的回調(diào)函數(shù)
getJSON("/posts.json").then(function(posts) {
// ...
}).catch(function(error) {
// 處理 getJSON 和 前一個回調(diào)函數(shù)運行時發(fā)生的錯誤
console.log("發(fā)生錯誤!", error);
});
上面代碼中,getJSON方法返回一個 Promise 對象,如果該對象狀態(tài)變?yōu)閞esolved,則會調(diào)用then方法指定的回調(diào)函數(shù);如果異步操作拋出錯誤,狀態(tài)就會變?yōu)閞ejected,就會調(diào)用catch方法指定的回調(diào)函數(shù),處理這個錯誤。
4.2另外,then方法指定的回調(diào)函數(shù),如果運行中拋出錯誤,也會被catch方法捕獲
p.then((val) => console.log("fulfilled:", val))
.catch((err) => console.log("rejected", err));
// 等同于
p.then((val) => console.log("fulfilled:", val))
.then(null, (err) => console.log("rejected:", err))
等同例子
1.const promise = new Promise(function(resolve, reject) {
throw new Error("test");
});
promise.catch(function(error) {
console.log(error);
});
// Error: test
// 寫法一
const promise = new Promise(function(resolve, reject) {
try {
throw new Error("test");
} catch(e) {
reject(e);
}
});
promise.catch(function(error) {
console.log(error);
});
// 寫法二
const promise = new Promise(function(resolve, reject) {
reject(new Error("test"));
});
promise.catch(function(error) {
console.log(error);
});
比較上面兩種寫法,可以發(fā)現(xiàn)reject方法的作用,等同于拋出錯誤。
4.3如果 Promise 狀態(tài)已經(jīng)變成resolved,再拋出錯誤是無效的。
const promise = new Promise(function(resolve, reject) {
resolve("ok");
throw new Error("test");
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
// ok
上面代碼中,Promise 在resolve語句后面,再拋出錯誤,不會被捕獲,等于沒有拋出。因為 Promise 的狀態(tài)一旦改變,就永久保持該狀態(tài),不會再變了。
4.5Promise 對象的錯誤具有“冒泡”性質(zhì),錯誤總是會被下一個catch語句捕獲
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個Promise產(chǎn)生的錯誤
});
上面代碼中,一共有三個 Promise 對象:一個由getJSON產(chǎn)生,兩個由then產(chǎn)生。它們之中任何一個拋出的錯誤,都會被最后一個catch捕獲。
4.6跟傳統(tǒng)的try/catch代碼塊不同的是,如果沒有使用catch方法指定錯誤處理的回調(diào)函數(shù),Promise 對象拋出的錯誤不會傳遞到外層代碼,即不會有任何反應(yīng)。
例子
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因為x沒有聲明 resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log("everything is great");
});
setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123
上面代碼中,someAsyncThing函數(shù)產(chǎn)生的 Promise 對象,內(nèi)部有語法錯誤。瀏覽器運行到這一行,
會打印出錯誤提示ReferenceError: x is not defined,但是不會退出進程、終止腳本執(zhí)行,2 秒之后還是會輸出123。
這就是說,Promise 內(nèi)部的錯誤不會影響到 Promise 外部的代碼,通俗的說法就是“Promise 會吃掉錯誤
4.6.1Node 有一個unhandledRejection事件,專門監(jiān)聽未捕獲的reject錯誤,上面的腳本會觸發(fā)這個事件的監(jiān)聽函數(shù),可以在監(jiān)聽函數(shù)里面拋出錯誤。
process.on("unhandledRejection", function (err, p) {
throw err;
});
上面代碼中,unhandledRejection事件的監(jiān)聽函數(shù)有兩個參數(shù),第一個是錯誤對象,第二個是報錯的 Promise 實例,它可以用來了解發(fā)生錯誤的環(huán)境信息 會終止程序
4.7const promise = new Promise(function (resolve, reject) {
resolve("ok");
setTimeout(function () { throw new Error("test") }, 0)
});
promise.then(function (value) { console.log(value) });
// ok
// Uncaught Error: test
上面代碼中,Promise 指定在下一輪“事件循環(huán)”再拋出錯誤。到了那個時候,Promise 的運行已經(jīng)結(jié)束了,所以這個錯誤是在 Promise 函數(shù)體外拋出的,會冒泡到最外層,成了未捕獲的錯誤
4.8一般總是建議,Promise 對象后面要跟catch方法,這樣可以處理 Promise 內(nèi)部發(fā)生的錯誤。catch方法返回的還是一個 Promise 對象,因此后面還可以接著調(diào)用then方法。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因為x沒有聲明 resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log("oh no", error);
})
.then(function() {
console.log("carry on");
});
// oh no [ReferenceError: x is not defined]
// carry on
上面代碼運行完catch方法指定的回調(diào)函數(shù),會接著運行后面那個then方法指定的回調(diào)函數(shù)。如果沒有報錯,則會跳過catch方法。
Promise.resolve()
.catch(function(error) {
console.log("oh no", error);
})
.then(function() {
console.log("carry on");
});
// carry on
4.9catch方法之中,還能再拋出錯誤。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因為x沒有聲明 resolve(x + 2);
});
};
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log("oh no", error);
// 下面一行會報錯,因為 y 沒有聲明
y + 2;
}).then(function() {
console.log("carry on");
});
// oh no [ReferenceError: x is not defined]
上面代碼中,catch方法拋出一個錯誤,因為后面沒有別的catch方法了,導(dǎo)致這個錯誤不會被捕獲,也不會傳遞到外層。如果改寫一下,結(jié)果就不一樣了。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log("oh no", error);
// 下面一行會報錯,因為y沒有聲明
y + 2;
}).catch(function(error) {
console.log("carry on", error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
上面代碼中,第二個catch方法用來捕獲前一個catch方法拋出的錯誤。
5.Promise.prototype.finally()
finally方法用于指定不管 Promise 對象最后狀態(tài)如何,都會執(zhí)行的操作。
下面是一個例子,服務(wù)器使用 Promise 處理請求,然后使用finally方法關(guān)掉服務(wù)器。
server.listen(port)
.then(function () {
// ...
})
.finally(server.stop)
5.1finally方法的回調(diào)函數(shù)不接受任何參數(shù),這意味著沒有辦法知道,前面的 Promise 狀態(tài)到底是fulfilled還是rejected。這表明,finally方法里面的操作,應(yīng)該是與狀態(tài)無關(guān)的,不依賴于 Promise 的執(zhí)行結(jié)果。
5.2Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => { throw reason })
);
};
上面代碼中,不管前面的 Promise 是fulfilled還是rejected,都會執(zhí)行回調(diào)函數(shù)callback。
從上面的實現(xiàn)還可以看到,finally方法總是會返回原來的值。
// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})
// resolve 的值是 2
Promise.resolve(2).finally(() => {})
// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})
// reject 的值是 3
Promise.reject(3).finally(() => {})
6.Promise.all()
Promise.all方法用于將多個 Promise 實例,包裝成一個新的 Promise 實例。
const p = Promise.all([p1, p2, p3]);
上面代碼中,Promise.all方法接受一個數(shù)組作為參數(shù),p1、p2、p3都是 Promise 實例
如果不是,就會先調(diào)用下面講到的Promise.resolve方法,將參數(shù)轉(zhuǎn)為 Promise 實例,再進一步處理。
(Promise.all方法的參數(shù)可以不是數(shù)組,但必須具有 Iterator 接口,且返回的每個成員都是 Promise 實例。)
6.1p的狀態(tài)由p1、p2、p3決定,分成兩種情況。
對的返回全部,錯的只返回第一個
(1)只有p1、p2、p3的狀態(tài)都變成fulfilled,p的狀態(tài)才會變成fulfilled,此時p1、p2、p3的返回值組成一個數(shù)組,傳遞給p的回調(diào)函數(shù)。
(2)只要p1、p2、p3之中有一個被rejected,p的狀態(tài)就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調(diào)函數(shù)。
// 生成一個Promise對象的數(shù)組
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON("/post/" + id + ".json");
});
Promise.all(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
上面代碼中,promises是包含 6 個 Promise 實例的數(shù)組,只有這 6 個實例的狀態(tài)都變成fulfilled,或者其中有一個變?yōu)閞ejected,才會調(diào)用Promise.all方法后面的回調(diào)函數(shù)。
const databasePromise = connectDatabase();
const booksPromise = databasePromise
.then(findAllBooks);
const userPromise = databasePromise
.then(getCurrentUser);
Promise.all([
booksPromise,
userPromise
])
.then(([books, user]) => pickTopRecommendations(books, user));
上面代碼中,booksPromise和userPromise是兩個異步操作,只有等到它們的結(jié)果都返回了,才會觸發(fā)pickTopRecommendations這個回調(diào)函數(shù)
6.2實例自己有reject不會觸發(fā)all的catch
const p1 = new Promise((resolve, reject) => {
resolve("hello");
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error("報錯了");
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 報錯了]
上面代碼中,p1會resolved,p2首先會rejected,但是p2有自己的catch方法,該方法返回的是一個新的 Promise 實例,p2指向的實際上是這個實例。該實例執(zhí)行完catch方法后,也會變成resolved,導(dǎo)致Promise.all()方法參數(shù)里面的兩個實例都會resolved,因此會調(diào)用then方法指定的回調(diào)函數(shù),而不會調(diào)用catch方法指定的回調(diào)函數(shù)。
如果p2沒有自己的catch方法,就會調(diào)用Promise.all()的catch方法。
const p1 = new Promise((resolve, reject) => {
resolve("hello");
})
.then(result => result);
const p2 = new Promise((resolve, reject) => {
throw new Error("報錯了");
})
.then(result => result);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// Error: 報錯了
7.Promise.race()
Promise.race方法同樣是將多個 Promise 實例,包裝成一個新的 Promise 實例。
返回值的是第一個改變狀態(tài)的返回值
7.1Promise.race方法的參數(shù)與Promise.all方法一樣,如果不是 Promise 實例,就會先調(diào)用下面講到的Promise.resolve方法,將參數(shù)轉(zhuǎn)為 Promise 實例,再進一步處理。
例子
,如果指定時間內(nèi)沒有獲得結(jié)果,就將 Promise 的狀態(tài)變?yōu)閞eject,否則變?yōu)閞esolve。
const p = Promise.race([
fetch("/resource-that-may-take-a-while"),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error("request timeout")), 5000)
})
]);
p
.then(console.log)
.catch(console.error);
上面代碼中,如果 5 秒之內(nèi)fetch方法無法返回結(jié)果,變量p的狀態(tài)就會變?yōu)閞ejected,從而觸發(fā)catch方法指定的回調(diào)函數(shù)。
8.Promise.resolve()
將現(xiàn)有對象轉(zhuǎn)為 Promise
const jsPromise = Promise.resolve($.ajax("/whatever.json"));
上面代碼將 jQuery 生成的deferred對象,轉(zhuǎn)為一個新的 Promise 對象。
Promise.resolve等價于下面的寫法。
Promise.resolve("foo")
// 等價于
new Promise(resolve => resolve("foo"))
8.1Promise.resolve方法的參數(shù)分成四種情況
(1)參數(shù)是一個 Promise 實例
如果參數(shù)是 Promise 實例,那么Promise.resolve將不做任何修改、原封不動地返回這個實例。
(2)參數(shù)是一個thenable對象
thenable對象指的是具有then方法的對象,比如下面這個對象。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
Promise.resolve方法會將這個對象轉(zhuǎn)為 Promise 對象,然后就立即執(zhí)行thenable對象的then方法。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
console.log(value); // 42
});
上面代碼中,thenable對象的then方法執(zhí)行后,對象p1的狀態(tài)就變?yōu)閞esolved,從而立即執(zhí)行最后那個then方法指定的回調(diào)函數(shù),輸出 42。
(3)參數(shù)不是具有then方法的對象,或根本就不是對象
如果參數(shù)是一個原始值,或者是一個不具有then方法的對象,則Promise.resolve方法返回一個新的 Promise 對象,狀態(tài)為resolved。
const p = Promise.resolve("Hello");
p.then(function (s){
console.log(s)
});
// Hello
上面代碼生成一個新的 Promise 對象的實例p。由于字符串Hello不屬于異步操作(判斷方法是字符串對象不具有 then 方法),返回 Promise 實例的狀態(tài)從一生成就是resolved,所以回調(diào)函數(shù)會立即執(zhí)行。Promise.resolve方法的參數(shù),會同時傳給回調(diào)函數(shù)。
(4)不帶有任何參數(shù)
Promise.resolve()方法允許調(diào)用時不帶參數(shù),直接返回一個resolved狀態(tài)的 Promise 對象。
所以,如果希望得到一個 Promise 對象,比較方便的方法就是直接調(diào)用Promise.resolve()方法。
const p = Promise.resolve();
p.then(function () {
// ...
});
上面代碼的變量p就是一個 Promise 對象。
需要注意的是,立即resolve()的 Promise 對象,是在本輪“事件循環(huán)”(event loop)的結(jié)束時執(zhí)行,而不是在下一輪“事件循環(huán)”的開始時。
setTimeout(function () {
console.log("three");
}, 0);
Promise.resolve().then(function () {
console.log("two");
});
console.log("one");
// one
// two
// three
上面代碼中,setTimeout(fn, 0)在下一輪“事件循環(huán)”開始時執(zhí)行,Promise.resolve()在本輪“事件循環(huán)”結(jié)束時執(zhí)行,console.log("one")則是立即執(zhí)行,因此最先輸出。
Promise.reject()
Promise.reject(reason)方法也會返回一個新的 Promise 實例,該實例的狀態(tài)為rejected。
const p = Promise.reject("出錯了");
// 等同于
const p = new Promise((resolve, reject) => reject("出錯了"))
p.then(null, function (s) {
console.log(s)
});
// 出錯了
上面代碼生成一個 Promise 對象的實例p,狀態(tài)為rejected,回調(diào)函數(shù)會立即執(zhí)行。
注意,Promise.reject()方法的參數(shù),會原封不動地作為reject的理由,變成后續(xù)方法的參數(shù)。這一點與Promise.resolve方法不一致。
const thenable = {
then(resolve, reject) {
reject("出錯了");
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
// true
上面代碼中,Promise.reject方法的參數(shù)是一個thenable對象,執(zhí)行以后,后面catch方法的參數(shù)不是reject拋出的“出錯了”這個字符串,而是thenable對象。
應(yīng)用
加載圖片
我們可以將圖片的加載寫成一個Promise,一旦加載完成,Promise的狀態(tài)就發(fā)生變化。
const preloadImage = function (path) {
return new Promise(function (resolve, reject) {
const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = path;
});
};
Generator 函數(shù)與 Promise 的結(jié)合
使用 Generator 函數(shù)管理流程,遇到異步操作的時候,通常返回一個Promise對象。
function getFoo () {
return new Promise(function (resolve, reject){
resolve("foo");
});
}
const g = function* () {
try {
const foo = yield getFoo(); console.log(foo);
} catch (e) {
console.log(e);
}
};
function run (generator) {
const it = generator();
function go(result) {
if (result.done) return result.value; return result.value.then(function (value) { return go(it.next(value)); }, function (error) { return go(it.throw(error)); });
}
go(it.next());
}
run(g);
上面代碼的 Generator 函數(shù)g之中,有一個異步操作getFoo,它返回的就是一個Promise對象。函數(shù)run用來處理這個Promise對象,并調(diào)用下一個next方法。
Promise.try()
實際開發(fā)中,經(jīng)常遇到一種情況:不知道或者不想?yún)^(qū)分,函數(shù)f是同步函數(shù)還是異步操作,但是想用 Promise 來處理它。因為這樣就可以不管f是否包含異步操作,都用then方法指定下一步流程,用catch方法處理f拋出的錯誤。一般就會采用下面的寫法。
Promise.resolve().then(f)
上面的寫法有一個缺點,就是如果f是同步函數(shù),那么它會在本輪事件循環(huán)的末尾執(zhí)行。
const f = () => console.log("now");
Promise.resolve().then(f);
console.log("next");
// next
// now
上面代碼中,函數(shù)f是同步的,但是用 Promise 包裝了以后,就變成異步執(zhí)行了。
那么有沒有一種方法,讓同步函數(shù)同步執(zhí)行,異步函數(shù)異步執(zhí)行,并且讓它們具有統(tǒng)一的 API 呢?回答是可以的,并且還有兩種寫法。第一種寫法是用async函數(shù)來寫。
const f = () => console.log("now");
(async () => f())();
console.log("next");
// now
// next
上面代碼中,第二行是一個立即執(zhí)行的匿名函數(shù),會立即執(zhí)行里面的async函數(shù),因此如果f是同步的,就會得到同步的結(jié)果;如果f是異步的,就可以用then指定下一步,就像下面的寫法。
(async () => f())()
.then(...)
需要注意的是,async () => f()會吃掉f()拋出的錯誤。所以,如果想捕獲錯誤,要使用promise.catch方法。
(async () => f())()
.then(...)
.catch(...)
第二種寫法是使用new Promise()。
const f = () => console.log("now");
(
() => new Promise(
resolve => resolve(f())
)
)();
console.log("next");
// now
// next
上面代碼也是使用立即執(zhí)行的匿名函數(shù),執(zhí)行new Promise()。這種情況下,同步函數(shù)也是同步執(zhí)行的。
鑒于這是一個很常見的需求,所以現(xiàn)在有一個提案,提供Promise.try方法替代上面的寫法。
const f = () => console.log("now");
Promise.try(f);
console.log("next");
// now
// next
事實上,Promise.try存在已久,Promise 庫Bluebird、Q和when,早就提供了這個方法。
由于Promise.try為所有操作提供了統(tǒng)一的處理機制,所以如果想用then方法管理流程,最好都用Promise.try包裝一下。這樣有許多好處,其中一點就是可以更好地管理異常。
function getUsername(userId) {
return database.users.get({id: userId})
.then(function(user) {
return user.name;
});
}
上面代碼中,database.users.get()返回一個 Promise 對象,如果拋出異步錯誤,可以用catch方法捕獲,就像下面這樣寫。
database.users.get({id: userId})
.then(...)
.catch(...)
但是database.users.get()可能還會拋出同步錯誤(比如數(shù)據(jù)庫連接錯誤,具體要看實現(xiàn)方法),這時你就不得不用try...catch去捕獲。
try {
database.users.get({id: userId})
.then(...)
.catch(...)
} catch (e) {
// ...
}
上面這樣的寫法就很笨拙了,這時就可以統(tǒng)一用promise.catch()捕獲所有同步和異步的錯誤。
Promise.try(() => database.users.get({id: userId}))
.then(...)
.catch(...)
事實上,Promise.try就是模擬try代碼塊,就像promise.catch模擬的是catch代碼塊。
9.Promise.reject()
10.應(yīng)用
11.Promise.try()
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/105837.html
摘要:示例運行函數(shù)彈出彈出函數(shù)接收參數(shù),返回值。其中,返回一個對象,是的返回值,代表函數(shù)是否執(zhí)行完成。 ES6特性介紹(下) ES6新的標(biāo)準(zhǔn),新的語法特征:1、變量/賦值2、函數(shù)3、數(shù)組/json4、字符串5、面向?qū)ο?、Promise7、generator8、ES7:async/await 《【W(wǎng)eb全棧課程二】ES6特性介紹(上)》見:https://segmentfault.com/a...
摘要:前言本文是對于異步系列第一篇里提到的模型中,所提到的任務(wù)隊列的展開分析正文說明以下代碼均使用瀏覽器運行關(guān)于瀏覽器表現(xiàn)的差異在最后做補充。的函數(shù)執(zhí)行過程,重復(fù)前面的步驟,因此輸出此時執(zhí)行棧和均為空,存儲著兩個的回調(diào)函數(shù)。 前言 本文是對于異步系列第一篇里提到的evenloop模型中,所提到的任務(wù)隊列(task queues)的展開分析 正文 說明:以下代碼均使用chrome瀏覽器運行 關(guān)...
摘要:異步執(zhí)行可以用回調(diào)函數(shù)實現(xiàn)。全成功也可以通過解構(gòu)數(shù)組的方式,將展開賦值??梢砸来文玫矫總€結(jié)果。放棄暫時放棄執(zhí)行相當(dāng)于創(chuàng)建了一個對象。代表是否完成,代表函數(shù)完成,已經(jīng)到終點。是因為最終的結(jié)果需要在最后的時候返回最終結(jié)果 prosime 在JavaScript的世界中,所有代碼都是單線程執(zhí)行的。由于這個缺陷,導(dǎo)致JavaScript的所有網(wǎng)絡(luò)操作,瀏覽器事件,都必須是異步執(zhí)行。異步執(zhí)行可以...
摘要:函數(shù)會在異步操作成功完成時被調(diào)用,并將異步操作的返回值作為參數(shù)傳遞到外部。方法的返回值方法總是返回一個新的對象,多次調(diào)用方法,默認(rèn)返回一個一個空的對象使用來來返回。 promise是什么 官網(wǎng)解釋 promise 表示一個異步操作的最終結(jié)果。 翻譯 ==可以將promise理解為一個狀態(tài)機==,它存在三種不同的狀態(tài),并在某一時刻只能有一種狀態(tài) pending 表示還在執(zhí)行 reso...
摘要:前言異步編程模式在前端開發(fā)過程中,顯得越來越重要。隨著新標(biāo)準(zhǔn)的到來,處理異步數(shù)據(jù)流又有了新的方案。接下來我們介紹這兩種處理異步編程的方案。仍在繼續(xù)執(zhí)行,但執(zhí)行結(jié)果將被丟棄。使得異步代碼看起來像同步代碼,再也沒有回調(diào)函數(shù)。 前言 異步編程模式在前端開發(fā)過程中,顯得越來越重要。從最開始的XHR到封裝后的Ajax都在試圖解決異步編程過程中的問題。隨著ES6新標(biāo)準(zhǔn)的到來,處理異步數(shù)據(jù)流又有了新...
閱讀 875·2021-11-12 10:36
閱讀 3476·2021-09-08 10:44
閱讀 2802·2019-08-30 11:08
閱讀 1463·2019-08-29 16:12
閱讀 2737·2019-08-29 12:24
閱讀 979·2019-08-26 10:14
閱讀 759·2019-08-23 18:32
閱讀 1242·2019-08-23 17:52