【问题标题】:Async await its showing undefined异步等待其显示未定义
【发布时间】:2019-08-07 15:34:13
【问题描述】:
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 调用它时它返回一个 undefined

【问题讨论】:

  • const result = data.recipes; 你没有用它做任何事情。您忘记将 this.result 设置为 result。在搜索功能的 then 回调中尝试 this.result = data.recipes;。这是关于变量范围的,您创建的 const 仅存在于您的函数中。

标签: async-await ecmascript-2017


【解决方案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());

【讨论】:

    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 2019-03-25
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    相关资源
    最近更新 更多