简体   繁体   English

为什么我的 Firebase 脚本挂在终端上?

[英]why is my Firebase script hanging in the terminal?

I'm writing a script to auto update firebase as I need to run this once a week我正在编写一个脚本来自动更新 firebase,因为我需要每周运行一次

I have a index.js file and im running node index.js to run it, all good我有一个 index.js 文件,我正在运行node index.js来运行它,一切都很好

I've commented out lots of the code but for now I'm just running我已经注释掉了很多代码,但现在我只是在运行

const calculateWinnings = () => {
    console.log('called me!')
    return firebaseApp
        .database()
        .ref(`data`)
        .once('value')
        .then((snapshot) => {
            console.log('snaph::', snapshot.val())
            return
        })
}


calculateWinnings()

this is doing what I expect in terms of it's running the function and returning me data from firebase这在运行函数并从 firebase 返回数据方面符合我的预期

however, the script hangs and never exits in the terminal with the cursor marker showing但是,脚本挂起并且永远不会在终端中退出并显示光标标记

when I comment out the firebase stuff, it does what I expect当我注释掉 firebase 的东西时,它符合我的预期

so I'm wondering how do I exit the script successfully or why is it hanging?所以我想知道如何成功退出脚本或者它为什么挂起? I'm return the promise so it should be resolving?我要返回承诺所以它应该解决?

The Firebase SDK performs all network and disk activity in a background thread. Firebase SDK 在后台线程中执行所有网络和磁盘活动。 When the calculateWinnings() returns, the then((snapshot) => { hasn't actually been called yet. For this reason it is good that the program doesn't exit yet, or you'd never see the console.log('snaph::', snapshot.val()) .calculateWinnings()返回时, then((snapshot) => {实际上还没有被调用。因此,程序还没有退出是好的,否则你永远不会看到console.log('snaph::', snapshot.val())

You can see this in action, by forcing the program to exit:通过强制程序退出,您可以看到这一点:

const calculateWinnings = () => {
    console.log('called me!')
    return firebaseApp
        .database()
        .ref(`data`)
        .once('value')
        .then((snapshot) => {
            console.log('snaph::', snapshot.val())
            return
        })
}

calculateWinnings()
process.exit();

If you run it like this, you'll see that the snapshot from the database is never logged.如果您像这样运行它,您将看到数据库中的快照从未被记录。

This is also the answer to how to handle it correctly: since you already return the promise from once() from your calculateWinnings method, you can wait for that to complete and then tell the process to exit:这也是如何正确处理它的答案:因为你已经从你的calculateWinnings方法中返回了来自once()的承诺,你可以等待它完成,然后告诉进程退出:

calculateWinnings().then(() => {
  process.exit();
});

Or if you're on a more modern Node.js version:或者,如果您使用的是更现代的 Node.js 版本:

const calculateWinnings = async () => {
  ... the function body is the same as you currently have
}

await calculateWinnings()
process.exit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM