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
可能是无穷大而且我不知道它的长度。我也对其他解决方案持开放态度。
谢谢!