Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return return from a promise callback with fetch? [duplicate]

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 meant to return the response as a json. I don't think it is doing that.

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

        });

    };
like image 942
Blaze349 Avatar asked Apr 10 '17 10:04

Blaze349


2 Answers

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 = new Headers();
    let options = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors'
    };
    return fetch(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 = new Headers();
    let options = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors'
    };
    return fetch(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
});
like image 159
Jaromanda X Avatar answered Oct 21 '22 00:10

Jaromanda X


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 = 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 with await:

let response = await ext.get("http://example.com");
like image 35
lonesomeday Avatar answered Oct 20 '22 23:10

lonesomeday