vue.js Promise.all中的传递数组和接收数组

4xrmg8kj  于 2023-03-03  发布在  Vue.js
关注(0)|答案(2)|浏览(132)

我有一个货币列表:

ETH: 0,
BTC: 0,
USD: 0,
UAH: 0,
EUR: 0,

完整代码:

data() {
    return {
      selected: 'USD',
      selected2: '',
      tickers: [
        {
          id: 1,
          name: 'USD'
        },
        {
          id: 2,
          name: 'EUR'
        },
        {
          id: 3,
          name: 'UAH'
        },
      ],
      ETH: 0,
      BTC: 0,
      USD: 0,
      UAH: 0,
      EUR: 0,
      result: null,
      value: 1,
      modalOpened: false,
      tickersNew: null,
      currency: null,
    }

获取这些货币的值:

async onChange() {
      const [result, ETH, BTC, USD, EUR, UAH] = await Promise.all([
        this.getValue(),
        this.getValue('ETH'),
        this.getValue('BTC'),
        this.getValue('USD'),
        this.getValue('EUR'),
        this.getValue('UAH'),
      ])
      this.result = result;
      this.ETH = ETH;
      this.BTC = BTC;
      this.USD = USD;
      this.EUR = EUR;
      this.UAH = UAH;
    },

    async getValue(selectedTo = this.selected2) {
      const API_KEY = 'API KEY HERE';
      const loadTicker = () =>
          fetch(
              `https://min-api.cryptocompare.com/data/price?fsym=${this.selected}&tsyms=${selectedTo}&api_key=${API_KEY}`
          ).then(r => r.json()).then(r => r[selectedTo]);
      return (await loadTicker())
    },

我怎样才能使货币价值 be in a array-['ETH ',' BTC','USD',' EUR','UAH']这样我就可以向数组中添加数据,并得到数组中的结果。谢谢。

bprjcwpo

bprjcwpo1#

这样,您就可以在coins对象中添加更多的股票代码,onChange将处理它们

data() {
  return {
    coins: {result: 0, ETH: 0, BTC: 0, USD: 0, UAH: 0, EUR: 0}
  }
},
async onChange() {
      const coins = Object.keys(this.coins)
      const result = await Promise.all(coins.map(str => this.getValue(str === 'result' ? '' : str)))
      coins.forEach((str, idx) => { this.$set(this.$data.coins, str, result[idx]) })
},
aoyhnmkz

aoyhnmkz2#

//一个示例(在任何框架之外)

let cids = ['ETH', 'BTC', 'USD', 'EUR', 'UAH']

function getCurrencies(arr) {
    let values = []
    values.push(getValue(arr[c])
    return values
}

let cc, promises = getCurrencies(cids)
for (cc=0; cc<promises.length; cc++) {
    let r = promises[cc].value
    // in r is value resolved each promise
    // 

}

相关问题