【问题标题】:how to get value from promise resolved?如何从解决的承诺中获得价值?
【发布时间】:2023-03-24 03:17:01
【问题描述】:

sn-p 是

var name = firebase.firestore().collection('users_info').doc(uid).get().then(async function(doc) { 
        const usr = await doc.data().name;
        console.log(usr);
        return  await(usr); 
});
console.log(name); 

name 记录以下内容

Promise {<pending>} __proto__: Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]: "hello"

和 usr 记录你好,请帮助我获取名称中的值。

【问题讨论】:

  • 所有async 函数都返回一个承诺——总是。因此,您的函数的调用者需要使用.then()await 从返回的promise 中获取值。没有办法解决这个问题。此外,return await(usr) 没有任何用处。它应该只是return usr。无论您是执行return usr 还是return await usr,您的函数都会返回一个promise。 async 函数将使返回值成为 promise 的解析值。知道当你的函数遇到第一个await 时,这就是函数返回承诺的地方,这也许很有用。

标签: javascript ecmascript-6 promise


【解决方案1】:

您想要链接 then/catch 来解析名称 promise,或者您可以将您拥有的整个块包装在 async/await 中,然后调用该函数:

            async function fetchData() {
                try {
                    var name = await firebase.firestore().collection("users_info").doc(uid).get();
                    const usr = await doc.data().name;
                    console.log(usr);
                    console.log(name);
                    return usr;
                } catch(e) {
                    console.log(e);
                }

            }

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多