第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在類中使用 async await 分配屬性但返回 null

在類中使用 async await 分配屬性但返回 null

紫衣仙女 2021-06-16 18:10:56
我有一個從一開始就_code設(shè)置為的類,null然后向 an 發(fā)出請求url以獲取結(jié)果。不知何故,我在分配了類的屬性代碼后,結(jié)果仍然給了我null。我做錯了什么?class R {    constructor() {        this._code = null;    }    get code() {        return this._code;    }    set code(value) {        this._code = value;    }    async makingRequests(id) {        await this.requestToGetCode(id);        // this gives me null        console.log(this.code, 'this.code in rquest');    }    async requestToGetCode(id) {        await request(url, async (error, response, body) => {            if (body !== 'found_no_results') {                switch (response.statusCode) {                    case 200:                        this.code = await JSON.parse(body);                        // this does give me the proper result though                        console.log(this.code, 'this.code in requestToGetCode');                        break;                    case 404:                        console.log('page not found');                        break;                    default:                        break;                }            } else {                console.log(body, id);            }        });    }}提前感謝您的任何幫助和建議。
查看完整描述

1 回答

?
守著星空守著你

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊

正如評論中提到的,請求庫不返回承諾,而是使用回調(diào)。您可以使用像request-promise這樣的庫來解決這個問題。但是,如果您出于某種原因不想這樣做,則此答案可能會對您有所幫助。


為了能夠?qū)?async/await 與 Request 庫一起使用,您需要手動將調(diào)用包裝在 Promise 中。


async requestToGetCode(id) {

    await new Promise((resolve, reject) => {

        request(url, (error, response, body) => {

            if (body !== 'found_no_results') {

                switch (response.statusCode) {

                    case 200:

                        this.code = JSON.parse(body);

                        // this does give me the proper result though

                        console.log(this.code, 'this.code in requestToGetCode');

                        resolve();

                        break;

                    case 404:

                        console.log('page not found');

                        reject('Not found');

                        break;

                    default:

                        // Reject all other cases

                        reject('Error');

                        break;

                }

            } else {

                // Reject as we do not receive the correct response

                console.log(body, id);

                reject('Error');

            }

        });

    });

}

本質(zhì)上,我們在這里創(chuàng)建了一個新的 Promise,它將為我們完成請求。在請求回調(diào)中,我們?nèi)缓蟾鶕?jù)結(jié)果調(diào)用resolve或reject。


查看完整回答
反對 回復(fù) 2021-06-18
  • 1 回答
  • 0 關(guān)注
  • 514 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號