Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回承诺表示承诺待定,节点js?_Javascript_Node.js_Promise - Fatal编程技术网

Javascript 返回承诺表示承诺待定,节点js?

Javascript 返回承诺表示承诺待定,节点js?,javascript,node.js,promise,Javascript,Node.js,Promise,我是Nodejs的新手,第一次致力于承诺,所以现在的背景是当我尝试返回承诺时,它显示了状态承诺。如何解决这个问题有人能指导我吗 下面是我调用函数的代码,该函数将返回一个承诺。粗体线条显示我希望返回承诺并存储在对象中的位置 for(let i = 0; i<responseArray.length; i++){ let dollar = { amount : 0

我是Nodejs的新手,第一次致力于承诺,所以现在的背景是当我尝试返回承诺时,它显示了状态承诺。如何解决这个问题有人能指导我吗

下面是我调用函数的代码,该函数将返回一个承诺。粗体线条显示我希望返回承诺并存储在对象中的位置

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);

}

您需要等待这些承诺得到解决,然后才能使用已解决的值

下面是对循环的一个小的重写,应该可以工作

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:12345}
——这在您希望console.log(“$”,…)时似乎很奇怪。。。因为控制台输出类似于

$ [ { amount: 1 }, { amount: 0.7782 } ]

考虑到两个结果,当然-看不到你的
responseArray
所以,我只是猜测,

输出是这样的:[{amount:Promise{}},{amount:Promise{},{amount:Promise{},{amount:Promise{},{amount:Promise{},{amount amount:Promise{},},{amount:Promise{},},{金额:承诺{},{金额:承诺{},{金额:承诺{},{金额:承诺{}]很明显,返回承诺会导致调用函数收到承诺,不是吗?我的意思是,如果返回
true
,调用函数会得到
true
,等等。无论如何,要得到承诺的解析值,需要使用承诺的
。然后
方法。承诺还没有实现。哟你需要等待
金额
承诺用
之类的东西来实现
在使用它的值之前等待
…也感谢您的解决方案没有显示任何输出。这意味着什么?
没有显示任何输出
-这是什么意思?您是说
控制台.log(“$”,dollarAmount)
从未被调用?可能发生了拒绝我添加了拒绝处理-会被调用吗?知道什么?我问了一个问题?!它没有收到任何拒绝。我尝试了你的拒绝处理。我将resolve方法放在setTimeout方法中,现在它显示未定义的值。这是否意味着我们会得到响应,但不是在要求的格式?
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: 1 }, { amount: 0.7782 } ]