Izle
Izle

Reputation: 117

Is there a way to wait for promise before continue?

I have some array of data and would like each of them to get some information.

I would like to log the console when the process starts and log the data when it finished, but the result gives me the same data as when initialized.

I have tried using async / await but it does not work as I expected.

Here is my Code

const data = [
  {
    name: 'User 1',
    detail: 0
  },
  {
    name: 'User 2',
    detail: 0
  },
  {
    name: 'User 3',
    detail: 0
  }
];

function getDetail() {
  setTimeout(() =>  {
        return "Detail Test";
   }, 3000);
}

async function mapping() {
  await Promise.all(data.map(async (item) => {
    item.detail = await getDetail();
  }))
}


console.log("Start");
mapping();
console.log(data);

the result is still the same.

[
  {
    name: 'User 1',
    detail: 0
  },
  {
    name: 'User 2',
    detail: 0
  },
  {
    name: 'User 3',
    detail: 0
  }
]

My expectation

[
  {
    name: 'User 1',
    detail: "Detail Test"
  },
  {
    name: 'User 2',
    detail: "Detail Test"
  },
  {
    name: 'User 3',
    detail: "Detail Test"
  }
]

Upvotes: 1

Views: 69

Answers (1)

Daniel
Daniel

Reputation: 6481

There are 3 problems with your code:

  1. getDetail should return a promise for await to actually wait.
const getDetail = () => new Promise((resolve) => {
  setTimeout(() =>  {
        resolve("Detail Test");
   }, 3000);
}
  1. Array.map does not modify the original array, which is highly recommended but for the sake of answering your question:
async function mapping() {
  await Promise.all(data.map(async (item, i) => {
    data[i].detail = await getDetail();
  }))
}
  1. Lastly, you'd want to await the mapping for the changes to take effect:
async function run() {
  console.log("Start");
  await mapping();
  console.log(data);
};

run();

Here's a working pen

Upvotes: 3

Related Questions