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调用它时它返回一个未定义的
你永远不会给state.search.result
分配任何东西
更换:
const result = data.recipes;
有:
this.result = data.recipes;
那就行了。但是,将值作为promise分辨率值返回是更好的设计:
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());