I will simply write down my thoughts below
function demo(){
let data=[];
fetch(xxx).then((res)=>{
data.push(res);
})
return data;
}
Since it is an asynchronous request, the returned data is still an empty array, not an array containing the requested data. So is there any way to get the data and then return it?
淡淡烟草味2017-05-19 10:22:15
It is impossible to return the value asynchronously
Values can only be processed in callback functions
ringa_lee2017-05-19 10:22:15
function demo(){
let data=[];
return fetch(xxx).then((res)=>{
data.push(res);
})
}
demo().then(data=>console.log(data))
过去多啦不再A梦2017-05-19 10:22:15
Use async/await method
async function demo(){
let data=[];
await fetch(xxx).then((res)=>{
data.push(res);
})
return data;
}
Then execute the function
黄舟2017-05-19 10:22:15
Use await, pay attention to the need to build
async function demo(){
const response = await fetch(url, options);
// todo: 异常处理
const data = await response.json();
return data;
}
Refer to es6 await