Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve the Syntax error : await is only valid in async function?

I have written a code to return some data from asynchronous call using promise. While I try to execute I get "Syntax Error await is only valid in async function" and also I get Cannot proxy application requests...Error: connect ECONNREFUSED.

I'm unsure why I get these errors

I have tried using async before the function calls, but it didn't work

var http = require('https');
var httpGet = function(url) {
  return new Promise (function(resolve, reject) {
    http.get(url,function(res) {
      res.setEncoding('utf8');
      var body = ''; 
      res.on('data', function(chunk){ 
        body += chunk;
        console.log("The body is "+ body);
      });
      res.on('end',function(){resolve(body);});
    }).on('error', reject);
  });
};

var body = await httpGet('link');
$.response.setBody(body);

I would want variable body to have the data returned from the httpGet function. Right now I'm getting the above mentioned errors. But without using await, I get the value of body as '{}'.

Please help

like image 457
Arun Elangovan Avatar asked Jun 20 '19 11:06

Arun Elangovan


1 Answers

await can only be called in a function marked as async. so, you can make an async IIFE and call the httpGet from there.

(async function(){
    var body = await httpGet('link');
    $.response.setBody(body);
})()

Basically when you use one asynchronous operation, you need to make the entire flow asynchronous as well. So the async keyword kindof uses ES6 generator function and makes it return a promise.

You can check this out if you have confusion.

like image 50
Aritra Chakraborty Avatar answered Oct 02 '22 09:10

Aritra Chakraborty