Необработанное отклонение обещания TypeError - PullRequest
1 голос
/ 04 июня 2019

Я использую async / await, чтобы сделать запрос к базе данных и получить результат, но я не знаю, почему у меня появляется эта ошибка в консоли браузера:

Необработанное отклонение обещанияTypeError: «игры не определены»

У меня есть две функции, асинхронная getData и вызов getGames:

getGames(){
    let query = HOMELF1_NEXT_GAMES;
    var data = {
        "query": query,
        "variables": null
    }
    fetch(URL_FEB_API, {
        method: "POST",
        headers: {
            "Accept"        :   "application/json",
            "content-type"  :   "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        return response.json()
    })
    .then(data => {
        console.log("End query");
        return data;
    })
    .catch(err => {
        console.log("Error: " + err)
    })
}

async getData(){
    console.log("Before getGames");
    let games = await this.getGames();
    console.log("After getGames");
    console.log("games: " + games.length)
}

componentDidMount(){
    this.getData();
};

И в консоли браузера яполучил этот результат:

enter image description here

Почему здесь не работает async / await?Что я делаю не так?

1 Ответ

1 голос
/ 04 июня 2019

Вы просто забыли return

getGames(){
    let query = HOMELF1_NEXT_GAMES;
    var data = {
        "query": query,
        "variables": null
    }
     \/ here
    return fetch(URL_FEB_API, {
        method: "POST",
        headers: {
            "Accept"        :   "application/json",
            "content-type"  :   "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        return response.json()
    })
    .then(data => {
        console.log("End query");
        return data;
    })
    .catch(err => {
        console.log("Error: " + err)
    })
}

async getData(){
    console.log("Before getGames");
    let games = await this.getGames();
    console.log("After getGames");
    console.log("games: " + games.length)
}

componentDidMount(){
    this.getData();
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...