所以我是 Javascript 新手(主要是 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()
时,它会立即返回一个 promise ,该 promise 将在工作完成时解析。 then()
也返回一个 Promise,catch()
也是如此。您将在 name
从回调接收到值之前返回它,这会在一段时间后发生。
如果你想编写一个函数,让调用者接收某些异步工作的结果,你应该返回一个用工作结果解析的 Promise,然后调用者可以使用 then()
promise 倾听结果。
基本上,您必须更加熟悉 JavaScript 用于处理异步工作和 promise 的约定。
关于javascript - JS - 无法返回数据库返回的对象(使用 firebase firestore),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54207799/