0

I'm struggling with using .map and await. How do I get the below to wait until the map has completed?

export async function buildDeviceArray(userIdList){ //userIdList is an array of ids
await userIdList.map(myFunction2)
return deviceArray1 // returns straight away, rather than waiting for the .map to complete

async function myFunction2(item) {
    let user =  await wixData.get("OurUsers", item)
    let device = await wixData.get("Devices", user.deviceDefault)
    let output =  { "label": device.deviceReference, "value": user.deviceDefault }
    if (user.deviceDefault) deviceArray1.push(output)
    console.log(deviceArray1);
    return
}
  • 1
    you would have to write a custom `.map` function that deals with having the callback function return promises. the default `.map` function is not asynchronous, and simply populates the array with whatever is returned for each value -- so at this point, the result of your `.map` would just be an array of promises – TKoL Sep 16 '20 at 08:16
  • 1
    looking at @Oyeme response, actually looks like `Promise.all` is the salvation here – TKoL Sep 16 '20 at 08:18

1 Answers1

1

This is an example of how you could use .map with an async callback function.

var originalArray = [1,2,3,4];

async function multiplyBy2(x) {
  await new Promise(r => setTimeout(r, 5000)); // half second
  return 2*x;
}

async function run() {
  var promiseArray = originalArray.map(multiplyBy2)
  var answerArray = await Promise.all(promiseArray);
  console.log(answerArray);
}

run();
TKoL
  • 13,158
  • 3
  • 39
  • 73