【发布时间】: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