search

Home  >  Q&A  >  body text

javascript - The function contains a fetch request. How to return the result of the fetch request through the function?

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中文网2818 days ago796

reply all(4)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:22:15

    It is impossible to return the value asynchronously

    Values ​​can only be processed in callback functions

    reply
    0
  • ringa_lee

    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))

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再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

    reply
    0
  • 黄舟

    黄舟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

    reply
    0
  • Cancelreply