我试图根据数据库中是否已经存在共享密钥来获取它。我正在使用Firebase商店数据库。
问题是,即使我在子函数中为passkey分配了一些值,但当我在函数之外执行console.log时,它只是打印在声明时设置的原始密码键。
我尝试使用window.passkey和window.global.passkey,在所有函数之外将passkey声明为全局变量,但没有工作。
我正在处理一个node.js项目。我的代码如下:
// var passkey = {"shared_key":""} // Declaring passkey as global variable but didn't work.
const onSubmit = (formData) => {
const email_id = getUserDetails().email;
const from_db = db.collection(email_id);
const to_db = db.collection(formData.to);
var passkey = {"shared_key": ""};
// Check if there exists a shared key between `from` and `to`
// Checking for shared key in either of the db is enough.
to_db.doc(email_id).get().then((res) => {
// assume that res.exists is true.
if (res.exists) {
passkey.shared_key = res.data().shared_key; // passkey is set here
} else {
// Generate and use a shared key
...some code to generate a shared key ...
passkey.shared_key = generated_key;
}
});
console.log(passkey);
// above prints {"shared_key": ""} instead of printing the value of shared key taken from the database.
// or the one that is generated!
};我知道这与javascript中的变量提升有关,但我认为必须有一些解决办法。如有任何帮助或评论,我们将不胜感激。提前谢谢。
发布于 2021-03-20 12:56:12
当您使用此模式编写代码时
function doIt () {
var something = ''
invokeFunction()
.then (function handleResult (result) {
console.log('2', something)
something = result
} )
console.log('1', something)
}您的console.log('1', something)在调用内部函数之前运行(为了清晰起见,我将其命名为handleResult )。这是因为invokeFunction()是异步的;它返回一个Promise object。
您可以重写如下:
async function doIt () {
var something = await invokeFunction()
console.log('1', something)
}得到你想要的结果。
恕我直言,除非您花时间学习异步/等待和承诺,否则编写Javascript将非常困难。在这方面,Javascript语言与其他语言非常不同。放下一切,现在就学会那些东西。我是认真的。
https://stackoverflow.com/questions/66721546
复制相似问题