所以我正在学习如何使用firebase admin sdk,但遇到了一个我不太了解的问题可以解决。基本上,我查询了数据库,并获得了要更新为相同值的一部分用户。因此,我将要更新的每个用户的ID存储在一个数组中,现在我试图遍历该数组并更新每个用户。但是我在实现这一部分时遇到了问题,这与.update()返回promise的事实有关,我不是100%如何在循环中处理此问题...
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp()
exports.getAllUsers = functions.https.onRequest((request, response) => {
const db = admin.firestore()
const users = db.collection('users').where('role', '==', 'artist').get()
.then(function (querySnapshot) {
//const users = querySnapshot.data()
const promises = []
querySnapshot.forEach(function (doc){
promises.push(doc)
})
return Promise.all(promises) //returning promises sends the resolved results to
}) //to the next .then()
.then(function (person){
let results = []
person.forEach(function(personSnap){
//const data = personSnap.data()
results.push(personSnap.id)
})
return results // results is the array of ids to update
})
//This .then() is where I have trouble understanding how to update
.then(function (ids){
for(var i = 0; i<ids.length; i++){
var artistsRef = db.collection('users').doc(ids[i]);
artistsRef.update({ //Should not be a return statement. This fixed my problem. Otherwise it would update the first user in the array and then leave the for loop.
'free_credits': '2'
})
}
return 'finished'
})
.then(function(reply) {
return response.send(reply)
})
.catch(function (error){
response.send(error)
})
})
我觉得我应该返回'artistsRef.update()',因为这是一个承诺,但我认为这会导致意外的结果。
如果我不返回update(),则ESLint会引发错误:“每个then()应该返回一个值或抛出”
答案 0 :(得分:2)
在发送响应之前,您要从最后的 def remove_value(self, value):
try:
index = self.find(value)
self.remove_at(index)
except ValueError:
raise NotFound()
def find(self, value):
if self.check_if_list_is_sorted() == True:
high = self.size
lst = self.arr[:]
index = self.search_with_binary(lst, value, 0, high)
return index
def search_with_binary(self, lst, value, low, high):
if low > high:
raise Empty()
else:
middle = (high + low) // 2
if value == lst[middle]:
return lst.index(value) # lst[middle]
elif value < lst[middle]:
return self.search_with_binary(lst, value, low, middle - 1)
else:
return self.search_with_binary(lst, value, middle + 1, high)
def remove_at(self, index):
'''Removes from the list an item at a specific location'''
if self.size == 0:
raise Empty()
elif index > self.size-1:
raise IndexOutOfBounds()
else:
for i in range(self.size - (index + 1)):
self.arr[index] = self.arr[index+1]
index += 1
self.size -= 1
self.arr[self.size] = 0
return self.arr
回调中提前返回。也许您应该添加另一个then()
,以便在完成所有最终更新后发送结果。