【问题标题】:How can I access the value returned by a promise?如何访问 promise 返回的值?
【发布时间】:2020-05-26 10:30:17
【问题描述】:

我是 stackoverflow 的新手,我已经处理了好几天的问题。我有下一段代码:

let comptot = function (value, data) {
     return fetch(API_TOT)
    .then(response => response.json())
    .then((data) => {
        let x = data[0].cantidad;
        console.log(x);
        return x;
    })
    .catch(error => {
        console.log("el error es el siguiente", error)
    })}

问题是我无法访问它返回的值。它确实将值 (230) 记录到控制台,但我想将该值显示到表中(我正在使用 Tabulator),它只返回:

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

我已经阅读了一堆非常相似的问题,但我不知道如何解决它。我也有点理解 Promise 的工作原理,但显然我没有理解所有内容,否则我不会遇到这个问题(我还阅读了一些关于 Promise 的文章,并观看了数十个关于 Promise 的 YouTube 视频,但仍然一无所获)。我还尝试将 Async Await 与以下代码一起使用,但遇到了完全相同的问题:

let comtot = async function (value, data) {
    let response = await fetch(API_TOT);
    let com = await response.json();

    console.log(com[0].cantidad);
    return com[0].cantidad;
}

请帮我解决这个问题,我真的很感激!

【问题讨论】:

  • 请在也是异步等待函数的函数中使用 comptot 函数,或者在打印前等待 promise 解决,即使用 '''comptop().then(result=>console.log)或尝试使用 console.log(await comptop()) ,注意异步等待只能在函数内部工作。
  • async 函数返回一个 Promise。你可以return com,然后使用.then
  • 另外,这是您问题中最受欢迎的重复:stackoverflow.com/questions/14220321/…
  • 您从使用 await.then() 调用的函数返回的承诺中获取值。这是你唯一的两个选择。所有async 函数都返回一个promise,因此您始终必须在该返回值上使用await.then() 来获取该值。

标签: javascript mongodb promise es6-promise tabulator


【解决方案1】:

有了这个sn-p,

let comptot = function (value, data) {
     return fetch(API_TOT)
    .then(response => response.json())
    .then((data) => {
        let x = data[0].cantidad;
        console.log(x);
        return x;
    })
    .catch(error => {
        console.log("el error es el siguiente", error)
    })
}

comptot 引用了您提到的Promise 对象,要提取其值,请使用.then() API,

comptot.then(res => {
  console.log("Resolved value", res);
}).catch(err => {
  console.log("Rejected value: ", err)
})

详细了解 promises 及其 .then() API

【讨论】:

  • 好的,现在我想我可能正在返回数据,至少正在打印到控制台。我做了你和 cmets 的人告诉我做的所有事情(比如使用 .then() 返回数据,感谢那个人!)但我无法让 Tabulator 显示表格上的值。我正在尝试使用 mutator 来执行以下代码,但无法让它显示数据:mutator: comtot().then((res) =&gt; { console.log(res); return res; })
  • 我对制表符不是很熟悉,但我建议阅读有关 Promise 和相关 API 的 MDN 文档。永远记住,“一个 Promise/它的 .then()/ .catch()/ 或相关的 API 总是会返回一个 Promise”
【解决方案2】:

*这与我发布的另一个问题的答案相同。我不知道我的代码出了什么问题,所以我针对我认为不相关但我错了的两件事发布了两个不同的问题。

我想通了,问题是在 Tabulator 中,表中的 mutator 从另一个来源获取数据,而不是从表的其余部分获取数据,因此当 mutator 开始工作时,表已经构建,并且我发现mutator在被触发时需要尽快的数据,但是它的源数据还没有准备好,所以我所做的就是使用:

function delayIt() {table.setData(API_URL)} setTimeout(delayIt, 1000)

因此,在构建表时,来自 mutator 源的数据已经可用,所以当 mutator 被触发时,它一切正常。很抱歉,如果它令人困惑,我无法弄清楚如何解释其他方式。

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2017-12-20
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多