gpt4 book ai didi

javascript - 如何让这个 for...of 循环停止并等待然后再继续? (JavaScript 异步/等待与 Firestore 监听器)

转载 作者:行者123 更新时间:2023-12-02 23:41:53 25 4
gpt4 key购买 nike

该函数处理单词数组。如果它在我们的字典中找到一个单词,它就会继续查找下一个单词。如果它在我们的字典中找不到该单词,则会向我们的 Firestore 数据库写入单词请求。然后,它设置一个监听器来监听要写入 Firebase 数据库的单词响应。当响应被写入时,监听器被分离。这大约需要两秒钟。此代码迭代单词数组,而不等待单词响应。我如何告诉它在继续下一个单词之前等待单词响应?

$scope.requestWords = function() {

async function processWordRequests() {
for (let word of $scope.wordsArray) {
console.log(word);
var doc = await firebase.firestore().collection('Dictionaries').doc($scope.longLanguage).collection("Words").doc(word).get()
if (doc.data() === undefined) {
console.log("Didn't find " + word + " in L2 dictionary.");

await firebase.firestore().collection('Users').doc($scope.user.uid).collection($scope.longLanguage).doc('Word_Request').set({
word: word,
requestOrigin: $scope.longLanguage + ':' + $scope.movieTitle + ':' + $scope.clipInMovieModel
})
console.log("Requested " + word);

await firebase.firestore().collection('Users').doc($scope.user.uid).collection($scope.longLanguage).doc('Word_Response').onSnapshot(function(doc) {
console.log("Listening for response...");
if (doc.data().word === word) {
console.log(word + " added to L2 dictionary.");
firebase.firestore().collection('Users').doc($scope.user.uid).collection($scope.longLanguage).doc('Word_Response')
.onSnapshot(function (){
console.log("Listener unsubscribed.")
// How do I make it wait here before going on to the next word?
return;
});
}
else {
console.log("Still listening...")
}
});

} else {
console.log("Found " + word + " in L2 dictionary.");
}
}
}

processWordRequests();
};

最佳答案

您需要使用 promise 或 promise 您的代码。

你有这行代码:

    await firebase.firestore().collection('Users').doc($scope.user.uid).collection($scope.longLanguage).doc('Word_Response').onSnapshot(function(doc) {

在右侧的哪个方向(请使用换行符以提高可读性)您有 .onSnapshot(function(doc) { ,我不确定,但我会guess 不会返回一个 promise ,所以你不能等待它。

相反,你可以用一个 promise 来包装它,比如......

await new Promise((resolve, reject)=> {
firebase.firestore().collection('Users').doc($scope.user.uid).collection($scope.longLanguage).doc('Word_Response').onSnapshot(function(doc) {
...
resolve("value-to-return-to-await").
...
});

您可以通过这个独立的培训类(class)了解有关 Promise 的更多信息:https://github.com/stevekane/promise-it-wont-hurt

关于javascript - 如何让这个 for...of 循环停止并等待然后再继续? (JavaScript 异步/等待与 Firestore 监听器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029549/

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