模块返回空数组

时间:2018-09-02 03:05:39

标签: javascript node.js async-await lodash

我有一个简单的模块返回,该调用通过一堆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);
}

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

2 个答案:

答案 0 :(得分:1)

问题是getCandles()无法知道每批异步函数lodash.forEach()何时创建解析。

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

请参见以下示例。

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

答案 1 :(得分: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
      }
    };
  });
}