forEach循环内的异步API调用 [英] async API call inside forEach loop

查看:600
本文介绍了forEach循环内的异步API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个似乎无法解决的问题,我想我在异步行为方面缺少了一些要点.

I ran into a problem that I cannot seem to solve, I'm guessing I'm missing some points in terms of async behaviour.

任务相对简单:具有不同货币的钱夹需要转换为单一货币.我想从以下API获取汇率:

The task is relatively simple: A wallet with money in different currencies needs to be transformed into a single currency. I want to get the exchange rate from following API:

> https://free.currencyconverterapi.com/api/v5/convert? q = $ {from} _ $ {to}& compact = y

https://free.currencyconverterapi.com/api/v5/convert?q=${from}_${to}&compact=y

以$ {from}为起始货币,$ {to}为目标货币.

With ${from} being the starting currency and ${to} the target currency.

我将不同的货币存储在一个名为positions的对象中,如下所示:

I store the different currencies in an object called positions, that looks like this:

[
    {'currency': "EUR",
    "amount": 10},
    {'currency': "CNY",
    "amount": 100},
  ]

因此,任务是将100EUR和100CNY转换为美元.

So the task would be to transform the 100EUR and 100CNY in for example USD.

要收集汇率,我想遍历以下函数中的单个头寸:

To gather the exchange rates, I want to iterate through the single positions in following function:

    collectExRates(targetCurrency) {
    let exRatesDict = {}
    this.positions.forEach( (position) => { 
      exRatesDict[position.currency] = this.parseUrl(position.currency, targetCurrency)
    });
    return exRatesDict
}

并且使用parseUrl:

And with parseUrl being:

    parseUrl(from, to) {
    const exRateName = from + '_' + to;
    var rate;
    return fetchUrl(`https://free.currencyconverterapi.com/api/v5/convert?q=${from}_${to}&compact=y`, function(error, meta, body){
            rate = JSON.parse(body)[exRateName].val
            console.log("RATE", rate)
            return rate
        });
}

我已经尝试了几件事(例如创建异步forEach,Promises,异步等待等),但我无法获得预期的结果,即返回将货币映射到其各自货币的汇率字典.汇率.

I already tried a couple of things (like creating an async forEach, Promises, async await, etc.), but I just can not get the intended result, which is to return the exchange rates dictionary mapping a currency to it's respective exchange rate.

非常感谢您的帮助.

推荐答案

问题是异步方法返回Promise,您需要等待它们解决.接下来的常见模式是

The problem is that async methods returns Promise and you need to wait them to resolve. The common pattern to do this is next:

Promise.all(arr.map(v => someAsyncFunc(v))).then((resolvedValues) => {
  resolvedValues.forEach((value) => {
    // Do your stuff here
  });
});

因此,基本上,您是在初始化一堆异步调用,等待它们通过Promise.all解析,并且仅在对解析的数据执行一些操作之后.

So basically you are initializing bunch of async calls, waiting for them to resolve with Promise.all and only after that preform some operations on resolved data.

这篇关于forEach循环内的异步API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆