0

I have following code with async function download_file(), its working correctly only where runs as single, but in loop, it's not waiting end of iteration. https://pastebin.com/PRgJRn9i

(async () => {

  for (let year of years) {
    for (let month of months) {
        for (let r of day_rng) {
           await download_file(year, month, r);
          }
    }
  }

})();
2
  • Looks like it should work. How do you invoke it? You should invoke it with the await keyword. Commented Jul 2, 2020 at 19:36
  • Oh, it's being invoked immediately. Try adding await (async () => {. Not all versions of node support await at the top level, so you may have to refactor a bit. Commented Jul 2, 2020 at 19:38

2 Answers 2

1

i am assuming you want each iteration to wait for the download_file function to end, if so then your download_file function should return a Promise that resolved whenever you are done downloading and done writing the contents as per your code, currently its not returning anything so the await before it won't do anything.

Sign up to request clarification or add additional context in comments.

7 Comments

How to make such promise?
something like this: return new Promise((resolve, reject) => { // your code goes here ..... /// you can pass whatever data you want to resolve or reject if you need any /// when everything is done and success resolve() /// if error reject() })
It's already returning a promise because it's async. Just adding async to a function makes it return a promise (even if it's a promise with no value).
@user2740650 hmm that's true, i didn't see that he defined the download_file function as async as well, but if he added an await before the self invoking function that will make node wait until all downloads are done, right ? not wait for each one, if that makes sense.
Hence my answer saying just to add await if he wants it to wait :) . If I'm interpreting correctly, should be a one-word fix. It's just that it calls the self invoking function but didn't wait for the returned promise to be resolved before running the rest of the script (which would just exit).
|
1

Simply add await to make nodejs wait for the result.

await (async () => {

  for (let year of years) {
    for (let month of months) {
        for (let r of day_rng) {
           await download_file(year, month, r);
          }
    }
  }

})();

1 Comment

Looks like you need at least Node version 14.3 according to medium.com/@pprathameshmore/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.