异步等待其显示未定义

时间:2019-03-16 21:08:55

标签: async-await ecmascript-2017

export default class Search {
constructor(query){
    this.query = query;
}

async getResults() {
    const API_KEY = "1d4e862be156056d16d3390378173c21";

    await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${this.query}`)
    .then(res => res.json())
    .then(data => {
        const result = data.recipes;
        console.log(result);
    })
    .catch(error => alert('Receive Data Failed'))

};

}

导入到这里。

const state = {};

const controlSearch =  async () =>{

    const query = 'pizza'

    if(query){

        state.search = new Search(query);

        await state.search.getResults();

        console.log(state.search.result);

    }
}

它将getResults方法中的数据存储到变量中。我想知道当我从state.search.result

调用它时,它返回的是未定义的

1 个答案:

答案 0 :(得分:1)

您永远不会为state.search.result分配任何内容

替换:

const result = data.recipes;

具有:

this.result = data.recipes;

可以解决问题。但是,最好将返回值作为承诺解决方案值进行设计:

getResults() { // drop the async; just return the promise
    const API_KEY = "1d4e862be156056d16d3390378173c21";

    return fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${this.query}`)
//  ^^^^^^
    .then(res => res.json())
    .then(data => this.result = data.recipes);
//                ^^^^^^^^^^^ (return it)
    .catch(error => alert('Receive Data Failed'))
};

在您的主要代码中:

    state.search = new Search(query);
    console.log(await state.search.getResults());