如何在异步调用中初始化类变量?

时间:2020-05-22 21:08:18

标签: javascript async-await this es6-class

我不是很明白为什么这段代码总是返回一个空数组。我有点理解它与javascript提升有关,但是我没有完全理解它。我最初将this.json设置为一个空数组,然后在getEvent()函数中将其初始化为fetch方法的响应。当我将结果记录到事件侦听器中的控制台时,我得到了响应对象,但是如果尝试在getEvent()函数中返回该对象,它将返回一个空对象。我尝试使用一种方法来检索this.json,但是我仍然得到一个空对象

class SearchPage {
    constructor(api_url, picture_url) {
        this.api_url = api_url;
        this.picture_url = picture_url;
        this.json = {};
    }

    getEvent() {
        window.addEventListener('load', async (event) => {
            let params = (new URL(document.location)).searchParams;
            let searchName = params.get('name')
            console.log(searchName)
            let params2 = new URL(document.location)
            console.log(params2)

            let search_api = "".concat('search', '/', searchName);
            const response = await fetch(this.api_url + search_api);
            this.json = await response.json();
            console.log(this.json)
        });
    }

    getJson() {
        return this.json;
    }
}

const api_url = "http://localhost:5000/"
const picture_url = "https://image.tmdb.org/t/p/";
const searchPage = new SearchPage(api_url, picture_url);

searchPage.getEvent()

const json = searchPage.getJson()
console.log(json)

0 个答案:

没有答案