javascript - The function contains a fetch request. How to return the result of the fetch request through the function?
PHP中文网
PHP中文网 2017-05-19 10:20:15
0
4
766

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?

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
淡淡烟草味

It is impossible to return the value asynchronously

Values ​​can only be processed in callback functions

左手右手慢动作
function demo(){
    let data=[];
    return fetch(xxx).then((res)=>{
        data.push(res);
    })
}
demo().then(data=>console.log(data))
过去多啦不再A梦

Use async/await method

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

Then execute the function

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template