Javascript 获取后如何返回结果?
任务是向imagesapi(pixabay)发出异步请求并返回数据。我想用fetch来做,对吗?但在这种情况下,我得到一个空的返回值。我能用它做什么Javascript 获取后如何返回结果?,javascript,json,asynchronous,async-await,fetch,Javascript,Json,Asynchronous,Async Await,Fetch,任务是向imagesapi(pixabay)发出异步请求并返回数据。我想用fetch来做,对吗?但在这种情况下,我得到一个空的返回值。我能用它做什么 函数myfunc(){ 获取(URL)。然后(函数(响应){ 返回response.json(); }).then(函数(hitsJSON){ hitsJSON.hits.forEach(项目=>{ 设resultItem={ id:item.id, url:item.previewURL, 标签:item.tags } 结果:推送(result
函数myfunc(){
获取(URL)。然后(函数(响应){
返回response.json();
}).then(函数(hitsJSON){
hitsJSON.hits.forEach(项目=>{
设resultItem={
id:item.id,
url:item.previewURL,
标签:item.tags
}
结果:推送(resultItem);
});
});
返回{
查询:查询,
图像:结果
};
}
通过扩展在myfunc()
中使用承诺的方式,可以返回获取请求的结果
通常的方法是从myfunc()
返回由fetch()
创建的承诺。这样,当您调用myfunc()
时,可以将函数处理程序添加到。然后()
中,在请求完成后执行该处理程序(以及获取结果):
function myfunc(){
// Add return here to return the fetch's promise
return fetch(URL).then(function(response) {
return response.json();
}).then(function(hitsJSON) {
var results = []
hitsJSON.hits.forEach(item => {
let resultItem = {
id: item.id,
url: item.previewURL,
tags: item.tags
}
results.push(resultItem);
});
// Return result here when request is complete
return {
query: 'query',
images: results
};
});
}
// Use myfunc() like this:
myfunc().then( function( results ) {
console.log(results)
})
您在哪里定义
结果
/查询
?