promise靜態(tài)方法resolve,reject



function ajax(url) {
    return new Promise(function(resolve, reject) {
        const xhr = new XMLHttpRequest();
        xhr.open('Get'); // 定義請求方式
        xhr.responseType = 'json'; // 定義返回值類型
        xhr.onload = function() {
            if(this.status === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        }
        xhr.send();
    })
}

// 情況一,Promise靜態(tài)方法傳入一個(gè)值
Promise.resolve('foo')
.then(function(res) {
    console.log(res); // foo
})

// 等價(jià)于
new Promise(function(resolve, reject) {
    resolve('foo');
})

// 情況二,Promise靜態(tài)方法傳入一個(gè)promise對(duì)象
const promise = api('/api/users.json');
const promise2 = Promise.resolve(promise);
// promise的靜態(tài)方法傳入一個(gè)promise,那他會(huì)原樣的返回傳入的promise對(duì)象
console.log(promise === promise2); // true

// 情況三:傳入一個(gè)對(duì)象,也帶有then,且then函數(shù)的參數(shù)也包含onFullFiled和onRejected兩種狀態(tài)的回調(diào),也是可以將其轉(zhuǎn)換成對(duì)應(yīng)的Promise對(duì)象的,如下:
Promise.resolve({
    // 這種帶then方法的對(duì)象,實(shí)現(xiàn)了一個(gè)thenable的接口,可以被then的對(duì)象;這在之前原生PROMISE對(duì)象沒普及時(shí),很多三方庫封裝promise對(duì)象時(shí)都會(huì)采用這種思想
    then: function(onFullFiled, onRejected) {
        onFullFiled('foo');
    }
})
.then(res => {
    console.log(res); // foo
})

// 快速創(chuàng)建一定是失敗的promise對(duì)象的靜態(tài)方法
Promise.reject(new Error())
.catch(error => {
    console.log(error);
})
// 無論傳入什么參數(shù)都會(huì)作為promise對(duì)象失敗的原因
Promise.reject(anything)
.catch(err => {
    console.log(err);
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容