我是 Nodejs 新手,第一次处理 Promise,所以现在的上下文是当我尝试返回 Promise 时,它显示状态 Promise 。如何解决这个问题有人可以指导我吗?
这是我调用将返回 promise 的函数的代码。粗体线显示我想要返回该 promise 并将其存储在对象中的位置。
for(let i = 0; i<responseArray.length; i++){
let dollar = {
amount : 0
};
if(i == 1){
continue;
}
dollar.amount = **currenciesService.getCurrencyLatestInfo(responseArray[i].currency);**
dollarAmount.push(dollar);
}
console.log("$", dollarAmount);
这是返回 promise 的代码。
const getCurrencyLatestInfo = function(currency) {
return new Promise(function(resolve, reject) {
request('https://min-api.cryptocompare.com/data/price?fsym='+currency+'&tsyms='+currency+',USD', { json: true }, (err, res, body) =>
{
if (err) {
reject(err);
} else {
var result= body;
resolve(result);
console.log("RESULT: ",result.USD);
}
});
})
}
最佳答案
您需要等待这些 promise 解决,然后才能使用解决的值
这是对循环的一个小重写,应该可以工作
let promises = [];
for(let i = 0; i<responseArray.length; i++){
if(i == 1){
continue;
}
let dollar = currenciesService.getCurrencyLatestInfo(responseArray[i].currency)
.then(amount => ({amount})); // do you really want this?
promises.push(dollar);
}
Promise.all(promises)
.then(dollarAmount =>console.log("$", dollarAmount))
.catch(err => console.error(err));
这应该会产生一个类似于 [{amount:123},{amount:234}]
的数组,正如您的代码所期望的那样
上面也可以简化为
Promise.all(
responseArray
.filter((_, index) => index != 1)
.map(({currency}) =>
currenciesService.getCurrencyLatestInfo(currency)
.then(amount => ({amount})) // do you really want this?
)
)
.then(dollarAmount =>console.log("$", dollarAmount))
.catch(err => console.error(err));
注意:您的原始代码建议您希望结果采用 {amount:12345}
的形式 - 当您想要 console.log("$", .... ) ...因为控制台输出类似于
$ [ { amount: 1 }, { amount: 0.7782 } ]
当然给出两个结果 - 看不到你的 responseArray
所以,我只是猜测
关于javascript - 返回 Promise 说 Promise Pending,Node js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216051/