0

I have a module exporting a function who's goal is to collect all streamed string data from a URL and return the complete result:

'use strict'
const http = require("http");
const bl = require("bl");

async function getUrlData (url) {
  http.get(url, (response) => {
    response
      .pipe(bl((err, data) => {
        if(err) return console.log(err);
        
        const stringData = data.toString();
        return stringData
      }));
  });
}

module.exports = getUrlData;

I also have a main file which accepts 3 URLs as arguments and attempts to print out the value from getting the data from each URL in the exact order given.

'use strict'
const getData = require('./http-collect-module');

const urls = process.argv.slice(2);

const main = async () => {
  urls.forEach((url) => {
    var stringData = await getData(url);
    console.log(stringData)
  });
}

main();

I'm trying to make one get complete before moving onto the next, however am receiving this error:

    var stringData = await getData(url);
                     ^^^^^

SyntaxError: await is only valid in async function

I cannot understand why I'm getting this error since the main function is an async one. Any help appreciated

user3895395
  • 471
  • 4
  • 16
  • Yes, `main` is async, but the callback function of `forEach` isn't. And `forEach` also doesn't support async callbacks. If you want to execute one promise after the other use a simple `for ..in` or `for .. of ` lop – derpirscher Mar 06 '22 at 22:13
  • ah that was it thanks! now getting undefined in each console.log but it's progress at least! – user3895395 Mar 06 '22 at 22:17
  • Your `getUrlData` function doesn't return anything ... – derpirscher Mar 06 '22 at 22:20

0 Answers0