javascript - 返回 Promise 说 Promise Pending,Node js?

标签 javascript node.js promise

我是 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/

相关文章:

javascript - Puppeteer 没有正常工作(浏览器未聚焦时暂停/卡住)

javascript - 如何获取当前登录用户authservice的用户名

javascript - 为每个带有类的 div 找到第三个父 div,然后向其添加 css

java - 使用 javascript 调用 get 函数

javascript - 为什么网络套接字在 nodejs 上表现不同?

mysql - Sequelize 创建并填充foreignKey

javascript - 根据ajax响应更改单选按钮值

javascript - Promise.allSettled typescript 数组推理

javascript - 黑客新闻 API - 获取最受欢迎的项目

javascript - 在图像上应用自定义 Jquery UI 调整大小 handle