async / await not working in combination with fetch

后端 未结 1 1104
臣服心动
臣服心动 2020-12-30 05:43

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

<         


        
相关标签:
1条回答
  • 2020-12-30 06:11

    You forgot to declare response as 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.

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

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题