模块返回空数组

问题描述 投票:1回答:2

我有一个简单的模块返回,它使一堆API调用检索数据然后返回它

export default async function getCandles(coins) {
  let data = [];
  _.forEach(coins, async coin => {
    let candles1h = await client.candles({
      symbol: coin,
      interval: "1h",
      limit: 500
    });
    let candles2h = await client.candles({
      symbol: coin,
      interval: "2h",
      limit: 500
    });
    let candles4h = await client.candles({
      symbol: coin,
      interval: "4h",
      limit: 500
    });
    let candles1d = await client.candles({
      symbol: coin,
      interval: "1d",
      limit: 500
    });

    let candles = {
      "1h": candles1h,
      "2h": candles2h,
      "4h": candles4h,
      "1d": candles1d
    };

    data.push({ coin: candles });
  });

  return data;
}

我有一个测试文件,它输入数组参数并发送它

async function test() {
  let candles = await getCandles(coins);

  console.log(candles);
}

当我调用测试函数时,输出只是一个空数组。我在这做错了什么?

javascript node.js async-await lodash
2个回答
1
投票

问题是getCandles()无法知道每个批次的异步函数lodash.forEach()何时创建结果。

一种解决方案可能是使用Promise.all()调用批量的异步函数。 Promise.all()awaitable,可以同时发送多个呼叫,而不是按顺序发送。

请参阅下面的粗略示例。

// Get Candles.
const getCandles = async symbol => {
  const intervals = ['1h', '2h', '4h', '1d']
  const limit = 500
  const candles = await Promise.all(intervals.map(async interval => await client.candles({symbol, interval, limit})))
  return candles.reduce(async (c, x, i) => {
    c[intervals[i]] = x
    return c
  }, {})
}

// Get Coins.
const getCoins = async symbols => {
  const coins = symbols.map(async symbol => ({coin: await getCandles(symbol)}))
  return await Promise.all(coins)
}

// Test.
const test = async () => await getCoins(symbols)

0
投票

我想我会这样做。但我不确定我没试过。

export default async function getCandles(coins) {
  return await _.map(coins, async coin => {
    let candles1h = await client.candles({
      symbol: coin,
      interval: "1h",
      limit: 500
    });
    let candles2h = await client.candles({
      symbol: coin,
      interval: "2h",
      limit: 500
    });
    let candles4h = await client.candles({
      symbol: coin,
      interval: "4h",
      limit: 500
    });
    let candles1d = await client.candles({
      symbol: coin,
      interval: "1d",
      limit: 500
    });

    return {
      coin: {
        "1h": candles1h,
        "2h": candles2h,
        "4h": candles4h,
        "1d": candles1d
      }
    };
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.