javascript async / await 不能与 fetch 结合使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32823277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:47:34  来源:igfitidea点击:

async / await not working in combination with fetch

javascriptasync-awaitfetch-apiecmascript-next

提问by Jeanluca Scaljeri

I'm trying to use ES7 async/ awaittogether with fetch. I know I'm close but I can't get it to work. Here is the code:

我正在尝试将 ES7 async/awaitfetch. 我知道我很接近但我无法让它工作。这是代码:

class Bar {
    async load() {
        let url =  'https://finance.yahoo.com/webservice/v1/symbols/goog/quote?format=json';
        try {
            response = await fetch(url);
            return response.responseText;
        } catch (e) {
            return e.message;
        }
    }
}

which I use as follows:

我使用如下:

let bar = new Bar();
bar.load().then(function (val) {
    console.log(val);
});

DEMO

演示

For some reason I always get into the catchwith the message

出于某种原因,我总是进入catch消息

response is not defined

Any suggestions what I do wrong ?

任何建议我做错了什么?

UPDATE: As suggested in the comments, it might be an issue with fetch, so I tried a simplified (ES5) version:

更新:正如评论中所建议的,这可能是一个问题fetch,所以我尝试了一个简化的(ES5)版本:

<!doctype html>

<html>
    <head>      
        <script>
            var url =  'https://finance.yahoo.com/webservice/v1/symbols/goog/quote?format=json';
            fetch(url, {method: 'get', mode: 'cors'}).then(function (response) {
                       console.log(response.responseText);
               });
        </script>
    <head>

   <body></body>
<html>

And still doesn't work :( However, if I replace fetch it works:

仍然不起作用:(但是,如果我替换 fetch ,它会起作用:

var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
console.log(request.responseText);

采纳答案by Bergi

You forgot to declare responseas a variable. Class code is always strict code, and you won't get away with assigning to implictly global variables. Instead, it throws a ReferenceError.

您忘记声明response为变量。类代码始终是严格的代码,您将无法逃避分配给隐式全局变量。相反,它会抛出一个ReferenceError.

Apart from that, Responseobjects don't have a responseTextproperty like a XHR, they do have a .text()method that waits for the body to be received and returns a promise.

除此之外,Response对象没有responseText像 XHR这样的属性,它们确实有一个.text()方法来等待主体被接收并返回一个承诺。

class Bar {
    async load() {
        let url =  'https://finance.yahoo.com/webservice/v1/symbols/goog/quote?format=json';
        try {
            let response = await fetch(url);
//          ^^^^
            return await response.text();
//                                ^^^^^^
        } catch (e) {
            return e.message;
        }
    }
}