最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - asyncawait not working in combination with fetch - Stack Overflow

programmeradmin6浏览0评论

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 =  '';
        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 ments, it might be an issue with fetch, so I tried a simplified (ES5) version:

<!doctype html>

<html>
    <head>      
        <script>
            var url =  '';
            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);

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./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 ments, it might be an issue with fetch, so I tried a simplified (ES5) version:

<!doctype html>

<html>
    <head>      
        <script>
            var url =  'https://finance.yahoo./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);
Share Improve this question edited Apr 19, 2016 at 17:34 Bergi 665k161 gold badges1k silver badges1.5k bronze badges asked Sep 28, 2015 at 12:41 Jeanluca ScaljeriJeanluca Scaljeri 29.1k66 gold badges232 silver badges379 bronze badges 6
  • 2 I think you're using fetch wrong - if fetch is this developer.mozilla/en-US/docs/Web/API/Fetch_API – Jaromanda X Commented Sep 28, 2015 at 12:45
  • Still not sure what is wrong. I've tried adding {method: 'get'} to the fetch call but didn't work. – Jeanluca Scaljeri Commented Sep 28, 2015 at 12:55
  • Also looks like you're hitting a CORS issue – Jaromanda X Commented Sep 28, 2015 at 12:55
  • I've updated the post with a es5 version + fetch which also doesn't work. I don't see any CORS arros – Jeanluca Scaljeri Commented Sep 28, 2015 at 13:07
  • I didn't say it was an "issue with fetch" ... I said "I think you are using fetch wrong" - that aside, finance.yahoo./webservice/v1/symbols definitely supplies zero CORS headers, so you are having a CORS issue – Jaromanda X Commented Sep 28, 2015 at 13:10
 |  Show 1 more ment

1 Answer 1

Reset to default 15

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./webservice/v1/symbols/goog/quote?format=json';
        try {
            let response = await fetch(url);
//          ^^^^
            return await response.text();
//                                ^^^^^^
        } catch (e) {
            return e.message;
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论