0
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-');

The purpose is to use countDistinctAsyncWords to print out the message that got fetched by the fake timeout api getMsgOneCharATime calling. I still not able to come out an idea how should I intercept each character correctly, assuming that the message can be infinity and I do not know the length of it. I am also open to other solutions.

Thanks!

ey dee ey em
  • 7,991
  • 14
  • 65
  • 121
  • Have you seen [this question](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises?rq=1)? *"assuming that the message can be infinity"* - The message could be infinitely long *if* the `getMsgOneCharAtATime()` always returned the *next* character from a theoretically infinite stream, but it doesn't, it returns the character at a specified index so you can only go up to the highest index that a JS number can represent. – nnnnnn Oct 04 '17 at 02:24
  • @nnnnnn thanks let me take a look! – ey dee ey em Oct 04 '17 at 10:57
  • @nnnnnn read through it, still can't see what part of that question be able to address this question... – ey dee ey em Oct 04 '17 at 19:41

0 Answers0