简体   繁体   English

firebase方法结束前另一个方法运行的问题reactjs

[英]Problem of another method runs before the firebase method finishes reactjs

First of all, this lambda works at the click of a button.首先,这个 lambda 只需单击一个按钮即可工作。 When I press the button as I refresh the page, I get an "undefined" message from the console.当我在刷新页面时按下按钮时,我从控制台收到一条“未定义”消息。 but when I wait for a short while (without refreshing the page) and click the button again, I can see the value I expected on the console.但是当我等待片刻(没有刷新页面)并再次单击按钮时,我可以在控制台上看到我期望的值。 For this, I thought of using sleep function, but I don't want to use it.为此,我想到了使用sleep function,但是我不想用。 Can I solve this with a mechanism used in multi-thread programs like lock/synchronized?我可以用锁/同步等多线程程序中使用的机制来解决这个问题吗?

and importantly, what is the reason for this?重要的是,这是什么原因?

Note that: I'm new to react and web development.请注意:我是新来的反应和 web 开发。

Code;代码;

const handleAddCarPark = () => {
    
    var dbRef = fire.database().ref("foo/bar/qux");
    var newParkID;
    var copy_count;

    dbRef.child("count").on("value", snapshot => {
        newParkID = parseInt(snapshot.val()) + 1000000;
        copy_count = parseInt(snapshot.val());
    });

    console.log(newParkID);
}

on() is asynchronous and returns immediately. on()是异步的并立即返回。 The callback will be invoked some time later when the query is complete, and again every time the data changes.回调将在查询完成后的某个时间被调用,并且每次数据更改时都会再次调用。

In JavaScript, there is only one thread.在JavaScript中,只有一个线程。 There is no need for locking or multithreading techniques.不需要锁定或多线程技术。 All code and callbacks are invoked on the single thread.所有代码和回调都在单个线程上调用。

Your code should expect to only use the results of the query from inside the callback that you pass to on() .您的代码应该只使用您传递给on()的回调内部的查询结果。

If you intend to only query a single time without listening for results that could change over time, you should be using once() instead of on() .如果你打算只查询一次而不监听可能随时间变化的结果,你应该使用once()而不是on() once() is also asynchronous, and returns a promise with the results of the query. once()也是异步的,并返回带有查询结果的 promise。 You should learn how to use these promises, as they are how you primarily handle asynchronous results in JavaScript.您应该学习如何使用这些承诺,因为它们是您在 JavaScript 中处理异步结果的主要方式。

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

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