什麼是promise
Promise 是一個對象,它代表了一個異步
操作的最終完成或者失敗。
Promise 構造函數包含一個參數和一個帶有 resolve(解析)和 reject(拒絕)兩個參數的回調。 在回調中執行一些操作(例如異步),如果一切都正常,則調用 resolve,否則調用 reject。
怎麼使用
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("ok!");
}
else {
reject(Error("failed"));
}
});
promise.then(function(result) {
console.log(result); // "ok!"
}, function(err) {
console.log(err); // Error:"failed"
});
XMLHttpRequest 執行 promise
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
簡寫,使用then
一個用於成功,一個用於失敗(即promise 執行和拒絕):
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
})
換成catch
get('story.json').then(function(response) {
console.log("Success!", response);
}).catch(function(error) {
console.log("Failed!", error);
})
換成finally
get('story.json').then(function(response) {
console.log("Success!", response);
}).catch(function(error) {
console.log("Failed!", error);
})
需要注意
執行程序應該只調用一個解析或一個拒絕。任何狀態的改變都是最終的。
所有進一步的操作和拒絕將被被忽略:
let promise = new Promise(function(resolve, reject) {
resolve("done");
reject(new Error("…")); // ignored
setTimeout(() => resolve("…")); // ignored
});
總結
使用了promise,在異步執行的流程中,把執行代碼和處理結果的代碼清晰地分離了。簡單的寫了一個promise的使用,大家可以仔細看下底下參考鏈接,想具體學習可以看阮一峯老師的ES6課程。
參考鏈接
https://developers.google.com/web/fundamentals/primers/promises?hl=zh-cn#top_of_page
https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://es6.ruanyifeng.com/#docs/promise