【发布时间】: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