如何构建一个承诺,使用超时模拟api从回调中正确检索数据?

时间:2017-10-04 02:19:02

标签: javascript asynchronous promise timeout settimeout

var message = "I like apple and sunny and crazy bannaas ... and lovey cats";

  var getMsgOneCharATime = function(cb, idx) {
    // Fetches a character from the message. Simulates an API call by adding a delay to the request.
      const apiDelay = 10;
      setTimeout(function() {
        cb(message[idx]);
      }, apiDelay);
  };




//// only after following line I can edit!
var countDistinctAsyncWords = function() {
  const messageArray = [];
  let currentIndex = 0;

  function getPromisedCounter(value) {
    return new Promise((resolve, reject) => {
      if (!value) {
        resolve({
          value,
          index
        });
      } else {
        reject('there is a error');
      }
    });
  }

  var counter = setInterval(() => {
    getMsgOneCharATime(getPromisedCounter, currentIndex);
    currentIndex ++;
  });


  function saveWord(word) {
    if (!word) clearInterval(counter);
    console.log(word);
    messageArray.push(word);
  }
  console.log(messageArray);
  return messageArray.join();
}


console.log('---');
console.log(countDistinctAsyncWords());
console.log('---end-');

目的是使用countDistinctAsyncWords打印出由假超时api message调用获取的getMsgOneCharATime。我仍然无法想出如何正确拦截每个角色,假设message可能是无穷大而且我不知道它的长度。我也对其他解决方案持开放态度。

谢谢!

0 个答案:

没有答案