欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS PromiseLike的判定與使用詳解

 更新時(shí)間:2023年11月23日 14:55:44   作者:fengyehongWorld  
本文主要介紹了JS PromiseLike的判定與使用詳解, 文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一. $.ajax()返回值遇到的問題

當(dāng)我們執(zhí)行如下js代碼時(shí),可以看到$.ajax()執(zhí)行后,得到的response對(duì)象并不為空,并且response對(duì)象的responseJSON屬性也確實(shí)是有值的。

但是,當(dāng)我們執(zhí)行response.responseJSON后,得到的居然是undefined。
并且我們使用await 對(duì)response對(duì)象等待后,得到的就直接是response.responseJSON中的值。

setTimeout(async () => {

    const response = $.ajax({
        url: "https://api.github.com/users/fengyehong123",
        type: 'GET',
    });
    console.log(response);
    console.log(response.responseJSON);  // undefined

    const result = await response;
    console.log(result);

}, 1000);

執(zhí)行效果如下:

在這里插入圖片描述

上述現(xiàn)象是因?yàn)?nbsp;$.ajax()得到的對(duì)象是一個(gè) Promise Like對(duì)象,Promise Like對(duì)象和ES6的new Promise()一樣,都是對(duì) Promise A+ 規(guī)范的實(shí)現(xiàn),因此可以使用 await 進(jìn)行等待。

二. Promise A+ 規(guī)范

官網(wǎng): https://promisesaplus.com/

ES6的new Promise()也好,$.ajax()函數(shù)返回的Promise Like對(duì)象也好,
都只是Promise A+規(guī)范的一種實(shí)現(xiàn),該規(guī)范告訴我們?nèi)绾巫约簩?shí)現(xiàn)一個(gè)Promise。

三. 判斷是否為PromiseLike

如果一個(gè)值的類型為 object 或者 function并且 該值還存在一個(gè)then方法那么 該值就是一個(gè) PromiseLike 對(duì)象。

// 判斷是否為 Promise Like
 function isPromiseLike(value) {

    if(value === null) {
        return false;
    }
    
    if ((typeof value === 'object' || typeof value === 'function') && (typeof value.then === 'function')){
        return true;
    }

    return false;
}

3.1 判斷ES6的new Promise()

ES6 的 new Promise() 是 Promise A+ 規(guī)范的實(shí)現(xiàn),所以肯定是一個(gè) PromiseLike 對(duì)象

const promise_obj = new Promise((resolve, reject) => {
    resolve('楓葉紅');
});
console.log(isPromiseLike(promise_obj) ? "promise_obj是PromiseLike對(duì)象" : "promise_obj非PromiseLike對(duì)象");

3.2 判斷包含then方法的對(duì)象

定義一個(gè)對(duì)象,對(duì)象里面有一個(gè)then方法,方法里面是耗時(shí)操作。符合該對(duì)象是一個(gè)Promise Like對(duì)象。

const then_response = {
    then: function(resolve, reject) {
        setTimeout(() => {
            resolve('賈飛天');
        }, 1000)
    }
}
console.log(
	isPromiseLike(then_response) 
	? "then_response是PromiseLike對(duì)象" : "then_response非PromiseLike對(duì)象"
);
// then_response是PromiseLike對(duì)象

(async (response) => {
    /*
        此處的response實(shí)際上是then_response
        因?yàn)?then_response 是一個(gè) Promise Like 對(duì)象
        要想await的話,必須包裹在 函數(shù)中
        因此此處定義了一個(gè)立即執(zhí)行函數(shù),還可以避免給函數(shù)取名的麻煩
    */
    const result = await response;
    console.log(result);
})(then_response);

3.3 判斷$.ajax()返回的對(duì)象

// ?兩秒之后發(fā)送ajax請(qǐng)求
setTimeout(async () => {

    const response = $.ajax({
        url: "https://api.github.com/users/fengyehong123",
        type: 'GET',
    });
    
    // 是一個(gè)PromiseLike對(duì)象
    console.log(
		isPromiseLike(response) ? "response是PromiseLike對(duì)象" : "response非PromiseLike對(duì)象"
	);
    // response是PromiseLike對(duì)象

    // 正因?yàn)槭?PromiseLike對(duì)象 ,所以才可以進(jìn)行await
    const result = await response;
    console.log(result);
}, 2000);

也就是說,我們之后的$.ajax()函數(shù)可以這么寫

// ajax的請(qǐng)求對(duì)象
const jqRequest = $.ajax({
    url,
    method: 'GET'
});

// doneCallBack,failCallBack,alwaysCallback 是從外部傳入的回調(diào)函數(shù)
jqRequest.done(function(data, textStatus, jqXHR) {
    doneCallBack && doneCallBack(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
    failCallBack && failCallBack();
}).always(function() {
    alwaysCallback && alwaysCallback();
});

也可以這么寫,從而可以避免回調(diào)的方式

document.querySelector('#btn').addEventListener('click', async function() {

    const url = "https://api.github.com/users/fengyehong123";
    // 后端的返回值
    let result = null;

    try {
        result = await $.ajax({
            url,
            type: 'GET',
        });
    } catch (error) {

        const {responseJSON} = error;
        console.log(`請(qǐng)求失敗!原因是: ${responseJSON}`);
    } finally {
        console.log("請(qǐng)求完成!");
    }

    if(!result) {
    	// 進(jìn)行相應(yīng)的業(yè)務(wù)處理
        return;
    }
   
    console.log("返回的最終值為:");
    console.log(result);
});

到此這篇關(guān)于JS PromiseLike的判定與使用詳解的文章就介紹到這了,更多相關(guān)JS PromiseLike內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論