Search code examples
javascriptnode.jses6-promise

How can i use Promises in For loop


const wiki = require('wikijs').default;
const { writeFileSync } = require("fs")
const dates = require("./getDates")
//December_23
for (let i = 0; i < dates.length; i++){
        wiki()
            .page(dates[i])
            .then(page => page.content()).then((value => {
                writeFileSync(`./data/${dates[i]}.json`,value)
                console.log(`${dates[i]} imported`)
        }
        )
        ).catch((err) => console.error(`${dates[i]} error\n${err}`))
}

I'm trying to get data from Wikipedia with wikijs using for loop. But for loop didnt wait for promise end how can i solve this


Solution

  • As you said, your loop execute your promise in the loop synchronously not asynchronously and what happens here is that your callback will be called with last index i in the loop because your loop will finish work and your callback will be called later

    You can work around this by creating a closure to save the index for every callback:

    One solution is to use forEach as it creates its own closure:

    dates.forEach((date, i) => {
       wiki.page(date).then(..........)
    })
    

    another solution is to create a IIFE inside your loop:

    for(let i = 0; i < dates.length; i++  ) {
      (function(i){
        //Your logic
      })(i)
    }