Home > Enterprise >  Update variable value for each iteration inside a promise
Update variable value for each iteration inside a promise

Time:10-18

I want to update the value of index. In this scenario there is job card with multiple services in it and every service have multiple employees in it. So I want to create a multidimensional object with services an array inside job card object and employees an array inside each service but my index variable is not updating.

Here is the code

await Promise.all(
  services.map(async (service) => {
    const labor = await new Promise((resolve, reject) => {
      connection.query(getLabor, [service?.labors_id], (err, result) => {
        resolve(result);
      });
    });
    rest.services.push(labor[0]);
    laborEmployee = service?.employees_id?.split(",");

    let index = -1;
    index = index   1;
    rest.services[index].employees = [];
    console.log(index);

    await Promise.all(
      laborEmployee.map(async (emp) => {
        const e = await new Promise(async (resolve, reject) => {
          connection.query(getEmployee, [emp], (err, result) => {
            if (err) throw err;
            rest.services[index]?.employees?.push(result[0]);
            resolve(result);
          });
        });
      })
    );
  })
);

But my index variable remains the same. Currently there are two iterations so index should be 0 and 1 but it remains 0 and 0.

CodePudding user response:

I'm not 100% sure just looking at the code, but my hunch would be to try defining the index variable outside of the scope of the initial await Promise.all as the way you have it currently, a new index is being defined for each Promise.

  • Related