函数中包含一个fetch请求,如何把fetch请求的结果通过函数return出去

下边我简单的写一下想法

function demo(){

let data=[];
fetch(xxx).then((res)=>{
    data.push(res);
})
return data;

}

由于是异步请求,所以return的data依然是空数组,而非包含请求数据的数组。那有什么办法在获取数据后再return出去呢?

阅读 5.4k
4 个回答

异步是不可能return值出去的

值只能在回调函数中处理

function demo(){
    let data=[];
    return fetch(xxx).then((res)=>{
        data.push(res);
    })
}
demo().then(data=>console.log(data))

使用async/await方式

async function demo(){
    let data=[];
    await fetch(xxx).then((res)=>{
        data.push(res);
    })
    return data;
}

然后执行该函数

用await,注意需要构建

async function demo(){
    const response = await fetch(url, options);
    // todo: 异常处理
    
    const data = await response.json();
    return data;
}

参考es6 await

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题