javascript - console.log() 显示正确的值,但是当将其分配给变量时,它是未定义的 - Angular,firestore

标签 javascript function asynchronous promise google-cloud-firestore

我正在开发 Angular 应用程序,想从 Firestore 获取一些数据。但是我的函数总是返回 undefined。但是,当我 console.log() 返回值之前,它会显示正确的值。

getToken(user_id) {
    this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token; //returns undefined!
      }
    });
}

两个值不应该相同吗?

最佳答案

看来您没有从函数中返回 Promise - getToken 函数中根本没有 return 语句,因此函数本身只返回 未定义。您拥有的内部返回声明将解决 promise ,这很好,但您必须处理该解决方案。

如果你像这样返回 promise :

getToken(user_id) {
    return this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token;
      }
    });
}

当 promise 通过执行以下操作解决时,您应该能够异步访问 user_token:

getToken(user_id).then(user_token => {
  handle_user_token_here(user_token);
});

注意:修改后的函数将返回一个 promise 。因此,您不能简单地执行以下操作:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
handle_user_token_here(user_token); // will not work.

不过你可以这样做:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
user_token.then(user_token => handle_user_token_here(user_token)); // will work

关于javascript - console.log() 显示正确的值,但是当将其分配给变量时,它是未定义的 - Angular,firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365265/

相关文章:

c - 如何在主 C 文件中使用第二个 C 文件中的函数?

javascript - 异步功能控制台日志记录乱序

javascript - xo Lint 错误 : `document` is not defined

javascript - Kendoui 如何动态地将 Kendo Angular 2 网格添加到面板栏?

asp.net - 如何为此 RC4 算法创建解密函数

javascript - lodash 中 throttle 和 debounce 的区别

javascript - 正则表达式允许十进制数大于 0 且小于 100

javascript - 第二次单击时如何不在单击事件中执行函数?

node.js - 尝试从 api 获取 token 时 Node 获取的错误行为

python - 为什么我要使用 `async def` 而不是 `@asyncio.coroutine`?