Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to console after async loop

I'm trying to do async loop, where I do something and after it ends, I write to the console. It's look like that:

const http = require('http');

async function load(link)
{
    try{
        http.get(link, response => console.log(`File: ${link}`));
    }catch(e){
        console.log('error');
    }
}

async function loop(arrayOfLinks)
{
    for(let link of arrayOfLinks)
        load(link);
}

module.exports = (arrayOfLinks) => {
    (async () => {
        await loop(arrayOfLinks);
        console.log('Files: '+arrayOfLinks.length);
    })();
}

But, what I have:

Files: 3
File: http://localhost:8000/1.jpg
File: http://localhost:8000/2.jpg
File: http://localhost:8000/3.jpg

And what I want:

File: http://localhost:8000/1.jpg
File: http://localhost:8000/2.jpg
File: http://localhost:8000/3.jpg
Files: 3

Questions:

  1. Why await operator doesn't block the next step?
  2. How can I solve this?

Thanks

like image 406
FLighter Avatar asked Feb 02 '26 08:02

FLighter


1 Answers

You need to make sure load function returns Promise. http.get by itself is not going to return it so you want to wrap it (or use promise based HTTP library, like fetch, etc).

Simple promise wrapper could look like this:

async function load(link) {
  try {
    return new Promise((resolve, reject) => {
      http.get(link, resolve).on('error', reject)
    })
    .then(response => console.log(`File: ${link}`))
  } catch (e) {
    console.log('error', e.message);
  }
}

async function loop(arrayOfLinks) {
  for (let link of arrayOfLinks)
    await load(link);
}

You also need to use await load(link) in loop.

like image 200
dfsq Avatar answered Feb 03 '26 23:02

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!