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

南笙酒味 提交于 2019-11-28 13:34:17

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

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!