返回承诺说Promise Pending,Node js?

时间:2018-03-11 02:26:59

标签: javascript node.js promise

我是Nodejs的新手并且第一次处理promises所以现在上下文是当我尝试返回promise它显示状态Promise时。如何修复它可以指导我完成这个任务吗?

这是我调用一个将返回一个promise的函数的代码。粗线显示我想要返回该承诺并存储在对象中的位置。

$inFile = 'D:\temp\feed.xml'
$outFile = 'D:\temp\feed-updated.xml'

# Read the input file into an in-memory XML document (object model).
$xml = [xml] (Get-Content -Raw $inFile)

# Loop over all <Product> elements (anywhere in the document)
# Note: Since we already have an in-memory XML document, using method
#       .SelectNodes() is more efficient than using the Select-Xml cmdlet.
#       Similarly, the use of collection operator .ForEach() is more efficient
#       than use of the ForEach-Object cmdlet.
$xml.SelectNodes('//Product').ForEach({

  # $_ is the <Product> element at hand, and its child elements
  # can simply be accessed with *dot notation*.

  # Get the model number...
  $modelNo = $_.ModelNumbers.ModelNumber

  # ... and use it to update the <ImageUrl> child element
  $_.ImageUrl = 'xxx.xxx.com/image/getdvimage/{0}/1/false/200/200/' -f $modelNo

})

# Save the modified in-memory XML document back to disk.
# Note: 
#   * Creates a file with BOM-less UTF-8 encoding.
#   * Be sure to use an *absolute* file path, because the .NET framework's
#     current directory typically differs from PowerShell's.
$xml.Save($outFile)

这是一个返回承诺的代码。

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

}

1 个答案:

答案 0 :(得分:1)

在使用已解决的值之前,您需要等待这些承诺解决

这里是你的循环的一个小的重写,应该工作

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时,这似乎很奇怪(&#34; $&#34;,....) ...因为控制台输出类似于

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

当然有两个结果 - 无法看到你的responseArray所以,我只猜测