Node.js Firebase函数的异步初始化
我必须在启动我的函数时做一些异步工作,例如从Google secrets Manager获取机密,并基于这些机密初始化客户端对象。我应该如何构造我的代码,使我的函数能够异步初始化,并且可以在不等待初始化对象的情况下访问它们?如果不遇到竞争条件,就无法保证在触发函数之前初始化已经完成Node.js Firebase函数的异步初始化,node.js,firebase,google-cloud-functions,serverless,Node.js,Firebase,Google Cloud Functions,Serverless,我必须在启动我的函数时做一些异步工作,例如从Google secrets Manager获取机密,并基于这些机密初始化客户端对象。我应该如何构造我的代码,使我的函数能够异步初始化,并且可以在不等待初始化对象的情况下访问它们?如果不遇到竞争条件,就无法保证在触发函数之前初始化已经完成await是somePromise的语法糖。然后(()=>/*下一位代码*/)是非阻塞的(如果您await某些内容,其他代码仍然可以执行,只是当前函数将暂停) 虽然您可以在其他语言中使用While循环来等待某个任务在另
await
是somePromise的语法糖。然后(()=>/*下一位代码*/)
是非阻塞的(如果您await
某些内容,其他代码仍然可以执行,只是当前函数将暂停)
虽然您可以在其他语言中使用While
循环来等待某个任务在另一个线程上完成,但JavaScript是单线程的,这样的While
循环将停止您的初始化代码运行。您需要使用回调或Promise
来正确执行此操作。在这两个选项中,我会选择Promise
方法。这将允许您调用await init()
,如果您将承诺缓存在init()
中,它可能在您需要使用该函数时已经完成,并且它将立即返回结果。这样就省去了处理包含所需数据的对象的生命周期管理、编写代码检查是否完成、处理初始化错误和将来遇到的麻烦
async function _initDoTheWork() {
/*
* Take care of any async initialization here,
* and return any result as applicable
*/
const app = firebase.initializeApp();
return { app }; // just as an example
}
/**
* Starts the initialization function, but
* caches its promise to reuse in future calls
*/
function initDoTheWork() {
if (!initDoTheWork.promise) {
initDoTheWork.promise = _initDoTheWork();
}
return initDoTheWork.promise;
}
// trigger async work now
// ignore result, but trap errors so you don't get an Unhandled Rejection Exception
initDoTheWork()
.catch((err) => {
// you could do nothing here, but I'd log the error somewhere
console.error("Pre-initialization reported an error", error)
});
export async function doTheWork() { // the actual function to be exported
const { app } = await initDoTheWork();
const db = app.firestore();
// do stuff with app & db
}
/**
* Force reinitialization of doTheWork()
*
* Note: Errors must be handled by the caller.
*/
doTheWork.reinitialize = async function reinitialize() {
initDoTheWork.promise = _initDoTheWork();
return initDoTheWork.promise;
}
这也可能是相关的。