[英]chaining functions one after the other with async await
我的函數應該截斷一個 firestore 集合,並在填充它之后,問題是在刪除所有文檔之前寫入了一些文檔。 我是 async await 的菜鳥,我的代碼有問題:
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 !");
幾個問題
您沒有將Promise.all
用於.map
所以它實際上並沒有做任何事情。 你也沒有從 with in 返回承諾
populate 方法正在使用 forEach,它不適用於承諾。 將其更改為用於for..of
像這樣的東西
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()
不會返回在所有異步刪除完成后解決的承諾。 而是return
返回的承諾delete().then().catch()
並應用Promise.all
上的返回值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);
});
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.