Skip to content Skip to sidebar Skip to footer

How To Return Return From A Promise Callback With Fetch?

I'm a bit stumped. I've forgotten how to do this. I have a function called ext.get() that takes a parameter of url. It fetches a response from the url. The ext.get() function is me

Solution 1:

If you need the response as JSON - and considering response.json() effectively the same as response.text().then(txt => JSON.parse(txt))

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

So, the function in full would be

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

That way you aren't essentially doing JSON.stringify(JSON.parse(json)) ... which is just json

However, I suspect you want a plain ol' javascript object

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

You would then use this as:

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

Solution 2:

You are using fetch, which is an asynchronous API. This means that your function must also be asynchronous -- i.e. it must return a Promise. (You could do this with a callback, but this is 2017...)

You can't return JSON from the function because the function will return before the response from the server is available. You must return a Promise and deal with it using then (or await) in your calling code.

The simplest and best way to do this here is simply to return the result of the fetch call once it has been transformed. You don't want to parse the JSON but to return it as a string. This requires the response.text() call:

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

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

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

And your calling code:

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

or with await:

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

Post a Comment for "How To Return Return From A Promise Callback With Fetch?"