How to return a return from feedback using fetch?

I'm a bit stumped. I forgot how to do this. I have a function called ext.get () that takes a url parameter. It receives a response from the url. The ext.get () function is designed to return the response as json. I don't think it is.

ext.get = (url) => {
        let myHeaders = new Headers();

        let options = {
            method: 'GET',
            headers: myHeaders,
            mode: 'cors'
        };

        //fetch get

        fetch(url, options).then(response => {
            console.log(JSON.stringify(response.json()))
            return JSON.stringify(response.json())

        });

    };

      

+3


source to share


2 answers


If you want the response as JSON - and consider response.json()

effectively the same asresponse.text().then(txt => JSON.parse(txt))

    return fetch(url, options).then(response => response.text());

      

So the complete function would be

ext.get = (url) => {
    let myHeaders = new Headers();
    let options = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors'
    };
    return fetch(url, options).then(response => response.text());
};

      

So you are not essentially doing JSON.stringify(JSON.parse(json))

... which is justjson



However, I suspect you want a simple "javascript" object.

ext.get = (url) => {
    let myHeaders = new Headers();
    let options = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors'
    };
    return fetch(url, options).then(response => response.json());
};

      

Then you would use it like:

ext.get('url').then(result => {
    // result is the parsed JSON - i.e. a plan ol' javascript object
});

      

+4


source


Used fetch

, which is an asynchronous API. This means that your function must also be asynchronous - i.e. She must return Promise

. (You can do this with a callback, but this is 2017 ...)

You cannot return JSON from a function, because the function will return before a response is received from the server. You should return a Promise and deal with it using then

(or await

) in your codebase.

The easiest and best way to do this is to simply return the result of the call fetch

after converting it. You don't want to parse the JSON, but return it as a string. This requires a call response.text()

:

ext.get = (url) => {
    let myHeaders = new Headers();

    let options = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors'
    };

    //fetch get

    return fetch(url, options).then(response => response.text());
};

      



And your calling code:

ext.get('http://example.com').then((response) => {
    console.log(response); // or whatever
});

      

or await

:

let response = await ext.get("http://example.com");

      

0


source







All Articles