This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                去年关闭。
        

    

因此,我是Java语言的新手(主要是Python人士),并且在理解某些真正奇怪的行为时遇到了麻烦。

长话短说-我正在尝试返回的数据库(firebase firestore)中有一个对象。在获取它之后,立即执行console.log,并在控制台中看到对象,它就在其中!但是,当我返回相同的对象时,它显示为“ noname” :(

这是代码

function load_name() {
    var db = firebase.firestore();
    var name = "noname";
    var docRef = db.collection("cities").doc("SF");
    docRef.get().then(function (doc) {
            if (doc.exists) {
                name = doc.data().name;
                //following shows as 'San Francisco' in console
                console.log(name);
                return name; //Added this line later to see if issue is fixed, but it didn't fix it.
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
            }
        }
    ).catch(function (error) {
        console.log("Error getting document:", error);
    });
    return name;
}
myname = load_name();
//^prints 'San Francisco' on console, but returns as undefined.


我花了大约5个小时。任何帮助,将不胜感激!

最佳答案

与python不同,JavaScript API都是异步的。当您调用get()时,它将立即返回并带有一个承诺,该承诺将在工作完成时解决。 then()还返回一个承诺,catch()也是如此。您要在name从回调收到值之前返回它,这会在一段时间后发生。

如果要编写一个函数,使调用者可以接收一些异步工作的结果,则应返回一个可以解决工作结果的promise,然后调用者可以对该请求使用then()来监听结果。

基本上,您将必须更加熟悉JavaScript用于处理异步工作和承诺的约定。

09-30 13:46
查看更多