firebase云函数调用回调



我正在使用firebase管理SDK为我的web应用程序创建新用户。

// function to create user and store additional info in firestore
exports.createUser = functions
.https.onCall((data, context) => {
admin.auth().createUser({
phoneNumber: data.phoneNumber,
displayName: data.displayName,
}).then((user) => {
// store data in firestore
admin.firestore().collection("user").doc(user.uid).set({...data});
}).catch((err) => {
// handle error
});
});

当我从客户端调用函数(将其附加到onClick事件(时,我想等到用户成功添加到firestore中,然后调用fetchUser函数,这样我就可以看到新添加用户的新数据列表。当前fetchUser被调用并刷新页面,但在刷新之前我看不到新添加的用户

const createUser = functions.httpsCallable('createUser');
const createNewUser = () => {
createUser({
phoneNumber: "+1111111111111",
displayName: "test",
introduction: "testcreate",
})
.then((res) => {
fetchUser(); // fetchUser just fetches user data from firestore and rerenders page 
})
.catch((err) => {
console.log(err);
});

};

总之,我能知道云功能何时完成工作并运行特定功能或任务吗

正如您将在关于"JavaScript承诺";在Firebase官方视频系列中,当所有异步操作完成时,您必须在后台触发、Pub/Sub或Callable Cloud Function中返回Promise或值。

这有两个相互关联的影响:

  1. 当异步操作完成时,它向云功能平台指示它可以终止并清理您的功能
  2. 相反,在异步操作完成之前,它向云功能平台指示在终止云功能之前应该等待

要返回Promise,由于您链接了几个异步Firebase Admin SDK方法(返回Promises(,因此需要返回Promise链,如下所示:

exports.createUser = functions.https.onCall((data, context) => {
return admin  // <== See return here
.auth()
.createUser({
phoneNumber: data.phoneNumber,
displayName: data.displayName,
})
.then((user) => {
// store data in firestore
return admin   // <== See return here
.firestore()
.collection('user')
.doc(user.uid)
.set({ ...data }); 
})
.then(() => {
// The set() method returns Promise<void>
// To send data back to the client, return data that can be JSON encoded
return { result: 'user created' };
})
.catch(error => {
// See https://firebase.google.com/docs/functions/callable#handle_errors
// on how to handle errors
});
});

这样,当您的前端返回CallableCloudFunction响应时,您可以确保用户和Firestore文档已经创建。


如果要使用async/await关键字,请执行以下操作。请注意,不建议将then()async/await混合使用。

exports.createUser = functions
.https.onCall(async (data, context) => {   // <== See async here
try {
const user = await admin.auth().createUser({
phoneNumber: data.phoneNumber,
displayName: data.displayName,
});
await admin.firestore().collection("user").doc(user.uid).set({ ...data });
return { result: 'user created' }

} catch (error) {
console.log(error);  // If desired
// See https://firebase.google.com/docs/functions/callable#handle_errors
// on how to handle errors
}
});

看看代码的可读性如何提高,就好像它是同步代码一样。

看起来您没有正确返回promise,因此函数在文档更新之前终止。请尝试添加返回语句,如下所示。

exports.createUser = functions
.https.onCall((data, context) => {
return admin.auth().createUser({
phoneNumber: data.phoneNumber,
displayName: data.displayName,
}).then(async (user) => {
// store data in firestore
await admin.firestore().collection("user").doc(user.uid).set({...data});
return {data: user.uid}
}).catch((err) => {
// handle error
return {error: error}
});
});

然后,理想情况下,您应该在所有承诺得到解决(即更新文件(后收到回复。还要确保您没有启用Firestore本地缓存。

最新更新