1

allDoc.map(function(stage){
      for(let key of stage.layerItem){
          //key.toImage is a library, so it only supports callback.
          key.toImage({
              callback(img) {
                  addPhoto(key.attrs)
              }
          });
      }
})

// Run when addPhoto is done
console.log("done")

async function addPhoto(params){
  const stored = await s3.upload(params).promise()
  return stored.Location
}

When the addPhoto function is completed, how do I proceed to the next code?

Fiit
  • 11
  • 2

2 Answers2

0

First wrap the toImage function in one that returns a promise then use Promise.all to wait for them all to settle.

(Community Wiki because this is close to being a duplicate question but has two distinct steps each of which has their own duplicate).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • i'm a beginner so I don't know, can you tell me how to use it? What I've done is this: – Fiit Jul 14 '21 at 15:52
  • let promise = new Promise(async function(resolve, reject) { key.toImage({ callback(img) { resolve(addPhoto(key.attrs)) } }); }) await Promise.all(promise).then(async result => { console.log("result",result) }) – Fiit Jul 14 '21 at 15:53
-1

One of the solutions I found for waiting .map() to be complete, is putting a Promise.all().

Your code should look like this:

const promisse = allDoc.map(function(stage, index){
    // Your loop
})

await Promise.all(promisse);

console.log('done');

Keep in mind that if your allDoc.map is inside another function, the upper function must be async.

m4el
  • 455
  • 1
  • 4
  • 14