我有一个Android应用程序,该程序将电话号码列表发送到项目中的Cloud Function。然后,服务器应该检索用户所有电话号码的列表,在两个数组之间获取一个交集(相同的元素),然后将交集数组中的用户的Firebase Auth用户ID发送回应用程序。>
这就是我想出的:-
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
const auth = admin.auth();
const _ = require('underscore');
exports.getUids = functions.https.onCall((data, context) => {
return auth.listUsers().then(userRecords => {
var allPhoneNumbers = [];
userRecords.users.forEach(user => allPhoneNumbers.push(user.phoneNumber));
var phoneNumbers = _.intersection(allPhoneNumbers, data);
var Uids = [];
//the next line is where I am nesting promises
phoneNumbers.forEach(phoneNumber => auth.getUserByPhoneNumber(phoneNumber).then(user => Uids.push(user.uid)));
return Uids;
}).catch(error => console.error(error));
});
我从未用JavaScript编程过,但我正在尝试。现在已经两天了,我只是想不通如何解决这个问题。我尝试了至少10种不同的方式。我发现诺言真的很难兑现。任何帮助表示赞赏。
答案 0 :(得分:2)
您可以使用Promise.all
来避免此问题。请注意,对getUserByPhoneNumber
的调用不会等待完成。您必须连锁承诺等待它。这是带有常规Promise的实现:
return auth
.listUsers()
.then(userRecords => {
var allPhoneNumbers = [];
userRecords.users.forEach(user => allPhoneNumbers.push(user.phoneNumber));
var phoneNumbers = _.intersection(allPhoneNumbers, data);
return Promise.all(
phoneNumbers.map(phoneNumber => auth.getUserByPhoneNumber(phoneNumber))
);
})
.then(users => {
return users.map(user => user.uid);
})
.catch(error => {
console.error(error);
});
这是一个使用async / await的实现:
return auth
.listUsers()
.then(async userRecords => {
var allPhoneNumbers = [];
userRecords.users.forEach(user => allPhoneNumbers.push(user.phoneNumber));
var phoneNumbers = _.intersection(allPhoneNumbers, data);
const users = await Promise.all(
phoneNumbers.map(phoneNumber => auth.getUserByPhoneNumber(phoneNumber))
);
return users.map(user => user.uid);
})
.catch(error => {
console.error(error);
});