Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - async / await not working in combination with fetch

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:

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 catch with the message

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:

<!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:

var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
console.log(request.responseText);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...