如何在javascript中获取对象的下一个和上一个元素?

时间:2018-11-28 12:45:36

标签: javascript arrays loops iterator iteration

对于一个示例交易应用程序,我有一个带有交易对符号的数组。我想获取更新,但是要按顺序执行,例如:

var pairList = ['BTCUSD', 'ETHBTC', 'ETHUSD'];
var currentPair = 0; // now pointing, that next time fetcher would fetch 'BTCUSD' pair
var candlesData = [];

update_current_pair = () {
  // for simplicity imagine that fetch io completes instantly, but it ALSO changes pairList
  candlesData[currentPair] = fetch_data_from_server_for_pair(currentPair);

  // pairList is changed, for example now 'BTCUSD' pair is removed.
  pairList = ['ETHBTC', 'ETHUSD'];

  // then i usually do:
  currentPair++; // increment
  currentPair %= pairList.length; // modulo
  // but OOPS! i just skipped 'ETHBTC' pair!

  setTimeout(update_current_pair, 1000);
}

// start fetcher
update_current_pair();

我如何不跳过“ ETHBTC”对?


示例代码:https://repl.it/@krieviedkoKtulk/jsasyncissue

所需:

updating BTCUSD
updated BTCUSD
updating ETHBTC
updated ETHBTC
updating ETHUSD
updated ETHUSD
updating ETHBTC
updated  ETHBTC

观察到:

updating BTCUSD
updated ETHBTC <- data from BTCUSD is put to ETHBTC by an error
updating ETHUSD <- fetching ETHBTC is skipped, but proceed to next ETHUSD
updated ETHUSD
updating ETHBTC
updated ETHBTC
updating ETHUSD
updated ETHUSD

1 个答案:

答案 0 :(得分:0)

不要从setTimeout()函数中调用update_current_pair(),只需使setInterval()开始,您将获得所需的输出。

因此从setTimeout(update_current_pair, 1000);中删除行update_current_pair(),并进行原始函数调用setInterval(update_current_pair, 1000);

update_current_pair = () => {
console.log('update called');
  console.log("updating " + pairList[currentPair]);
  // for simplicity imagine that fetch io completes instantly, but it ALSO changes pairList
  fetch_data_from_server_for_pair( () => {
      console.log("updated " + pairList[currentPair]);
      currentPair++; 
      currentPair %= pairList.length;
  } );
}

setInterval(update_current_pair, 1000);