gpt4 book ai didi

javascript - 循环中的链式 promise : Firebase read works fine, Firebase 写入不

转载 作者:行者123 更新时间:2023-11-30 14:46:44 25 4
gpt4 key购买 nike

我需要遍历 API 调用返回的数据并将其插入 Firebase。为了防止 Firebase API 过载和超时,我正在使用这种“链”技术来确保在进入下一个循环之前完成前一个循环及其所有 promise 。从 Firebase 读取/获取触发并返回预期结果。

写入/设置 Firebase 触发器,我知道这是因为“console.log(parents)”执行并显示正确的数据,“set”后面的“then”打印“Added student with ID”。但是,不会将任何数据写入云中的数据存储,也不会显示任何错误。如果我在循环和链之外单独运行写入/设置,它工作正常。

function writeDataToFirestoreStudents(data) {
let chain = Promise.resolve();
for (let i = 0; i < data.length; ++i) {
var parents = [];
chain = chain.then(()=> {
db.collection("parents").where("student_id", "==", data[i].kp_ID)
.get()
.then(function(querySnapshot) {
parents = [];
querySnapshot.forEach(function(doc) {
//console.log(doc.id, " => ", doc.data());
parents.push(doc.data().bb_first_name + " " + doc.data().bb_last_name);
});
return parents;
}).then(function(parents) {
console.log(parents);
var docRef = db.collection('students').doc(data[i].kp_ID);
var setAda = docRef.set({
bb_first_name: data[i].bb_first_name,
bb_last_name: data[i].bb_last_name,
bb_current_grade: data[i].bb_current_grade,
bb_class_of: data[i].bb_class_of,
parents: parents,
}).then(ref => {
console.log('Added student with ID: ', data[i].kp_ID);
});
}).catch(function(error) {
console.error("Error writing document: ", error);
});
})
.then(Wait)
}
}

function Wait() {
return new Promise(r => setTimeout(r, 25))
}

最佳答案

.批处理。这对我来说很好。

    pub.addToFirestore = function(){

var countries = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"},
{"name": "American Samoa", "code": "AS"},
{"name": "AndorrA", "code": "AD"},
{"name": "Angola", "code": "AO"},
{"name": "Anguilla", "code": "AI"},
{"name": "Antarctica", "code": "AQ"},
{"name": "Antigua and Barbuda", "code": "AG"},
{"name": "Zimbabwe", "code": "ZW"}
];
var db = firebase.firestore();
var batch = db.batch();

for (var i = 0; i < countries.length; i++) {
var newRef = db.collection("countries").doc(countries[i].code);
batch.set(newRef, {name: countries[i].name});
}

//Commit the batch
batch.commit().then(function () {
console.log("done");
});

};

关于javascript - 循环中的链式 promise : Firebase read works fine, Firebase 写入不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48790321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com