1

I am using an external API to create a set of folders in order.

chapters.forEach(function createFolder(chapter) {
  axiosInstance.post(folderCreateURL, {
      name: chapter,
      category_id,
    })
    .then(response => console.log(response))
    .catch(error => console.error(error));
});

Here chapters is an array which stores folder names. I need to iterate through this array, and create folders one by one. Ideally I want to call the next iteration of the loop in the then clause of the previous one - May be some kind of yield would work here, I am guessing.

So, can any one give me some pointers to help me make progress or point me to some resource that can help me solve the problem myself?

Siraj Samsudeen
  • 1,624
  • 7
  • 26
  • 35

1 Answers1

3

You could wrap this in a async function and use for loop to iterate (in the example below I use for..of)

Below snippet could help you

async function run() {
  for (let chapter of chapters) {
    try {
      const response = await axiosInstance.post(folderCreateURL, {
        name: chapter,
        category_id,
      })
      console.log(response)
    } catch (err) {
      console.error(error)
    }
  }
}

run()

Demo with fake data

function request(x) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(x)
    }, 500)
  })
}

async function run() {
  const chapters = [1, 2, 3, 4, 5]
  for (let chapter of chapters) {
    try {
      const response = await request(chapter)
      console.log(response)
    } catch (err) {
      console.error(error)
    }
  }
}

console.log('start')
run()
hgb123
  • 13,869
  • 3
  • 20
  • 38