Javascript Firebase云函数不使用Xstate执行任何操作
我正在尝试在Firebase上编写一个云函数,在编写另一个文档时更新Firebase中的文档。为此,我使用触发器方法onWrite。我使用Xstate来实现这一点,因为我的原始代码更复杂,但想法是一样的(问题也是一样)。这是我使用的代码(Typescript):Javascript Firebase云函数不使用Xstate执行任何操作,javascript,firebase,google-cloud-functions,xstate,Javascript,Firebase,Google Cloud Functions,Xstate,我正在尝试在Firebase上编写一个云函数,在编写另一个文档时更新Firebase中的文档。为此,我使用触发器方法onWrite。我使用Xstate来实现这一点,因为我的原始代码更复杂,但想法是一样的(问题也是一样)。这是我使用的代码(Typescript): import*作为“firebase函数”中的函数; 从“firebase管理员”导入*作为管理员; 从“xstate”导入{Machine,explain}; admin.initializeApp({}); //该功能将在公司所有者
import*作为“firebase函数”中的函数;
从“firebase管理员”导入*作为管理员;
从“xstate”导入{Machine,explain};
admin.initializeApp({});
//该功能将在公司所有者的产品更新后立即触发。
exports.productsOnUpdate=functions.firestore
.document(`companys/{companyId}/{products}/{productId}`)
.onWrite((更改:任意)=>{
完成=错误;
const PromiseFunction=(docIn:any)=>{
控制台日志(docIn);
返回管理员
.firestore()
.收集(“测试”)
.doc(“testdoc”)
.set({products:docIn.products},{merge:true})
.then((doc:FirebaseFirestore.WriteResult)=>doc.writeTime);
};
常量myMachine=Machine
绝对没有发生任何事情。当我在MyMachine的上下文中发生一个小错误时(将上下文:{doc:{products:{a product}}}
更改为上下文:{doc:{product:{a product}},
我确实看到了这一点:
因此,承诺处理似乎有问题。我已经花了一天时间在这方面;非常感谢您的帮助!您应该让xstate
解决您的承诺。从承诺函数中删除然后语句
:
const PromiseFunction=(docIn:any)=>{
控制台日志(docIn);
返回管理员
.firestore()
.收集(“测试”)
.doc(“testdoc”)
.set({products:docIn.products},{merge:true})
}
console.log(docIn)的结果是什么?
它甚至不执行该语句,所以它没有调试行。然后问题是你的机器
,你的代码也很臭,因为while(done==false);
我之所以使用while(done==false)
是因为云函数似乎已经返回“ok”(即finishing)当状态机仍在运行时。有什么不同的建议吗?您可以在完成作业时返回承诺和解决承诺有两件事出错:-Firebase不再正确执行函数。更改函数名称会产生不同的结果。-您的回答确实让它工作了。谢谢s!@PaulusPotter,太好了!我很高兴它帮助了你=)
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import { Machine, interpret } from "xstate";
admin.initializeApp({});
// This function will trigger as soon as a product of a company owner gets updated.
exports.productsOnUpdate = functions.firestore
.document(`companies/{companyId}/{products}/{productId}`)
.onWrite((change: any) => {
let done = false;
const PromiseFunction = (docIn: any) => {
console.log(docIn);
return admin
.firestore()
.collection("test")
.doc("testdoc")
.set({ products: docIn.products }, { merge: true })
.then((doc: FirebaseFirestore.WriteResult) => doc.writeTime);
};
const myMachine = Machine<any>({
id: "myMachine",
initial: "idle",
context: { doc: { products: "a product" } },
states: {
idle: {
on: {
INIT: "init"
}
},
init: {
invoke: {
id: "setDoc",
src: (context, event) => PromiseFunction(context.doc),
onDone: {
target: "success"
},
onError: {
target: "failure"
}
}
},
success: {},
failure: {}
}
}); // end of machine
const MyMachine = interpret(myMachine).onTransition(state => {
console.log(state.value);
// actually do something here
switch (state.value) {
case "INIT":
break;
case "success":
done = true;
console.log("Success");
case "failure":
console.log("Something went wrong");
default:
break;
}
});
MyMachine.start();
MyMachine.send("INIT");
while (done === false);
return "ok";
});