前端的一個(gè)必學(xué)知識(shí)之一,Promise對(duì)象,是一種用來(lái)解決異步編程的方案
const promise = new Promise(function(resolve, reject) { // ... some code if (/* 異步操作成功 */){ resolve(value); } else { reject(error); } }); promise.then(function(value) { // success }, function(error) { // failure });//then的第二個(gè)參數(shù)為可選
舉幾個(gè)例子
function timeout(ms) { return new Promise((resolve, reject) => { //setTImeout的第三個(gè)參數(shù),作為resolve函數(shù)的參數(shù) setTimeout(resolve, ms, 'done'); }); } //調(diào)用函數(shù),值100為setTImeout的時(shí)間,若異步狀態(tài)為fulfilled則返回傳遞給resolve的值 timeout(100).then((value) => { console.log(value); });
?
let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!'); // Promise // Hi! // resolved /*原因: *promise在創(chuàng)建后便會(huì)立即執(zhí)行,因此首先打印Promise *then返回返回異步回調(diào)函數(shù),所以執(zhí)行放在后面,因此Hi提前到第二個(gè)執(zhí)行 */
?
resolved
時(shí),則會(huì)調(diào)用then的回調(diào)函數(shù)getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... }); /* *上面的代碼使用then方法,依次指定了兩個(gè)回調(diào)函數(shù)。 *第一個(gè)回調(diào)函數(shù)完成以后,會(huì)將返回結(jié)果作為參數(shù),傳入第二個(gè)回調(diào)函數(shù)。 */
rejected
時(shí),則會(huì)調(diào)用catch回調(diào)函數(shù)const promise = new Promise(function(resolve, reject) { throw new Error('test');//拋出一個(gè)錯(cuò)誤,即狀態(tài)轉(zhuǎn)為reject }); promise.catch(function(error) { console.log(error);// Error: test });
?
const promise = new Promise(function(resolve, reject) { . . . }).then(function(){. . .})
.then(function(){. . .})
.catch(function(error){//處理前面promise對(duì)象以及回調(diào)的兩個(gè)then函數(shù)的錯(cuò)誤});
?幾個(gè)注意的點(diǎn),
a.catch函數(shù)返回為promise對(duì)象,所以后面也可以跟進(jìn)then函數(shù),但前面的catch函數(shù)不會(huì)捕獲后面的then函數(shù)的錯(cuò)誤
const promise = new Promise(function(resolve, reject) { . . . })
.catch(function(error){//處理前面promise對(duì)象的錯(cuò)誤})
.then(function(){...});//這里的then函數(shù)的錯(cuò)誤不會(huì)被catch捕獲,
?因此一般將catch函數(shù)寫(xiě)在所以then函數(shù)的后面,方便捕獲整個(gè)promise及then函數(shù)的錯(cuò)誤
b.catch函數(shù)也可以拋出錯(cuò)誤,但catch函數(shù)拋出的錯(cuò)誤只能由后一個(gè)catch函數(shù)捕獲
const promise = new Promise(function(resolve, reject) { . . . }) .catch(function(error){throw new Error('test');})//catch拋出一個(gè)錯(cuò)誤 .catch(function(){...});//這里的catch函數(shù)可以捕獲前面promise的錯(cuò)誤以及catch的錯(cuò)誤
?
7.promise.all()
用來(lái)將多個(gè)promise對(duì)象包裝成一個(gè)promise對(duì)象文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-711250.html
const p = Promise.all([p1, p2, p3]);
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-711250.html
到了這里,關(guān)于ES6---Promise對(duì)象的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!