Home > Net >  getting error 'await is only valid in async functions' from inside an asynchronous functio
getting error 'await is only valid in async functions' from inside an asynchronous functio

Time:07-23

I assume that this is because some other function that is not async is encasing it maybe? i cannot for the life of me work out what it could be though or how to fix it - (i am pretty much totally new to node so i apologise if this is a really basic question but i couldn't find an answer in any previously asked.)

here is the code:

http.createServer(async function (req, res) {
    let data = ''
    req.on('data', chunk => {
        data  = chunk;
    });
    req.on('end', () => {
        try {
            response =  await query();
        } catch (e) {
            response = e;
        }
        res.write(response);
        res.end();
    });
}).listen(8080);

in which query() is an async function that waits for a response from a bigquery server. the function works fine if placed before the first req.on('data') segment, but not if it is any later in the code than this. Any clues why?

Thanks in advance.

CodePudding user response:

I believe it is because it is nested that it is not receiving a promise back.

Not my answer but i can point you towards a solution given here: How to await and return the result of a http.request(), so that multiple requests run serially?

CodePudding user response:

The await keyword is in the unnamed function which occurs as second argument in req.on('end', () => {...}). To make that asynchronous, you must write:

req.on('end', async () => {
  let response; // your forgot to declare this local variable
  try {
    response = await query();
  } catch (e) {
    response = e;
  }
  res.write(response);
  res.end();
});

But I don't understand what your code does. You collect the data, but never use this?

  • Related