简体   繁体   中英

How to use nested functions using async and await?

I'm doing a admin script in my node backend includes mongo queries/updates and api calls. Im using async and await but it does not work as I want.

(async () => {
// connect to mongo (works ok)

 const products = await getProducts(); // Here I have my 10 elements

 await Promise.all(products.map(async (prod) => {
    response = await getProductInfo(prod.id);
  })); // here I call to getProductInfo ten times.

})()
  .catch(err => console.error(err));

const getProductInfo = async(idProduct) => {

  const response = await rq(optionsProductInfo); //request to API

  await Product.updateOne({ sku: response.sku }, { $set: {
    priority: response.priority,
    price: response.price,
  } });  // update product info
};

The problem is that the update in the database is not execute 10 times. Sometimes executed 2, 3, 4 times but never execute for the 10 elements.

Just make sure you're await ing the right thing, and that any function that has an await is itself async , and you should be just fine. The following code for example works just fine.

const products = [1,2,3,4,5,6];

async function updateRecord(data) {
  return new Promise((resolve, reject) => {
    // using timeout for demonstration purposes
    setTimeout(async() => {
      console.log("pretending I updated", data.id);
      resolve();
    }, 1000 * Math.random());
  });
};

async function getProductInfo(id) {
  return new Promise((resolve, reject) => {
    // again using timeout for demonstration purposes
    setTimeout(async() => {
      console.log("fake-retrieved product info for", id);
      resolve(await updateRecord({ id }));
    }, 1000 * Math.random());
  });
};

Promise.all(products.map(pid => getProductInfo(pid)))
       .then(() => console.log("we're done."));
       .catch(e => console.error("what?", e));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM