编程语言
首页 > 编程语言> > javascript – 如何使用fetch返回promise回调的返回值?

javascript – 如何使用fetch返回promise回调的返回值?

作者:互联网

参见英文答案 > How do I return the response from an asynchronous call?                                    35个
我有点难过.我忘记了怎么做.
我有一个名为ext.get()的函数,它接受url的参数.它从网址获取响应. ext.get()函数用于将响应作为json返回.我不认为这样做.

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

        });

    };

解决方法:

如果你需要响应为JSON – 并且有效地考虑response.json()与response.text().那么(txt => JSON.parse(txt))

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

所以,完整的功能将是

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

这样你基本上不做JSON.stringify(JSON.parse(json))…这只是json

但是,我怀疑你想要一个普通的’javascript对象

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

然后你会用它作为:

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

标签:fetch-api,javascript,ecmascript-6
来源: https://codeday.me/bug/20190929/1832282.html