我是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)记录到控制台,但是我想将该值显示到表中(我正在使用制表器),并且它仅返回:
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "230"
我已经阅读了一堆非常相似的问题,但我不知道该如何解决。我也很了解诺言如何运作,但是显然我什么都不懂,或者我不会遇到这个问题(我也阅读了很多关于诺言的文章,还看了几十部关于诺言的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;
}
[请帮助我解决这个问题,我会很感激的!
使用此代码段,
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)
})