简体   繁体   中英

chaining functions one after the other with async await

My functions should truncate a firestore collection and after populate it, the problem is that some documents are writtened after before all documents are deleted. I'm a noob with async await there is something wrong in my code :

let db = admin.firestore();

let truncateCollection = async function () {
    const snapshot = await db.collection(collectionToPopulate).get();
    await snapshot.docs.map(function (doc) {
        db.collection(collectionToPopulate).doc(doc.id).delete().then(function () {
            console.log("document supprimé : "+doc.id);
        }).catch(function (error) {
            console.error("erreur de suppression de document",error);
        });
    });
    await populate();
};

let populate = async function () {
    jsonInput.forEach(function (obj, index) {
        Object.entries(obj).forEach(([key,value]) => {
            //console.log(value);
            db.collection(collectionToPopulate).doc(key).set({
                name: value.name,
                imageUrl: value.image_url,
            }).then(function (docRef) {
                console.log("Document written with ID: ", key);
            }).catch(function (error) {
                console.error("Error adding document: ", error);
            });
        });
    });
};

truncateCollection();
res.send("Job Done !");

Couple of problems

  • You are not using Promise.all for .map so it is not really doing anything. Also you are not returning the promise from with in

  • THe populate method is using forEach which doesn't work with promises. Change that to use for..of

Something like this

const db = admin.firestore();

// eslint-disable-next-line func-style
const truncateCollection = async function () {
  const snapshot = await db.collection(collectionToPopulate).get();
  await Promise.all(snapshot.docs.map(function (doc) {
    return db.collection(collectionToPopulate).doc(doc.id).delete().then(function () {
      console.log(`document supprimé : ${doc.id}`);
    }).catch(function (error) {
      console.error("erreur de suppression de document", error);
    });
  }));
  await populate();
};

// eslint-disable-next-line func-style
const populate = async function () {
  for (const obj of jsonInput) {
    for (const [key, value] of Object.entries(obj)) {

      try {
        // eslint-disable-next-line no-await-in-loop
        const response = await db.collection(collectionToPopulate).doc(key).set({
          "name": value.name,
          "imageUrl": value.image_url
        });
        console.log("Document written with ID: ", key);
      } catch(err) {
        console.error("Error adding document: ", error);

      }
    }
  }
};

truncateCollection();
res.send("Job Done !");

docs.map() does not return a promise that resolves when all asynchronous deletions have been completed. Instead return the promise returned by delete().then().catch() and apply a Promise.all on the return value of docs.map() :

   await Promise.all(snapshot.docs.map(function (doc) {
        return db.collection(collectionToPopulate).doc(doc.id).delete().then(function () {
            console.log("document supprimé : "+doc.id);
        }).catch(function (error) {
            console.error("erreur de suppression de document",error);
        });
    }));

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