I am making a chrome extenction using JS. The function chrome.history.search is a async callback. Since it is async I plan to use promise to make it sync. I want the code to assign the value to url using chrome.history.search, and after that push it to the array lastEpisodeLink which is global. There is another function findLastEpisodeLink that calls findLastEpisode_helper on multiple title.
the output sequence which i need is :
start,
inside,
success,
start,
inside,
success, ...
but what i get is :
start, start, inside,success, inside, success
When i check the array lastEpisodeLink after the function has been run, it says empty which shouldn't be. How can I fix this?
Yes I have followed the answer How do I return the response from an asynchronous call? but still doesnt solves it. It would be very helpfull if you can help me fix this code. Thank you
function findLastEpisodeLink_helper(title) {
console.log("start");
var url;
function onSuccess () {
console.log('Success!');
lastEpisodeLink.push(url);
}
var promise = new Promise(function(resolve, reject) {
chrome.history.search(
{
'text': title,
'maxResults': 1,
'startTime': 0
},
function(historyItems) {
console.log("inside");
url = historyItems[0]["url"];
resolve();
});
});
promise.then(onSuccess);
}
The function which calls it
function findLastEpisodeLinks() {
for(title in stringArray) { //psudo code
findLastEpisodeLink_helper(title);
}
}
The function which calls it is as follow, it is itself a async callback, ALL calls is being done here by it.
chrome.history.search(
{
'text': '',
'maxResults': 10000,
'startTime': 0
},
function(historyItems) {
var allHistoryText = [];
var allHistoryUrl = [];
for(var i=0; i<historyItems.length; i++) {
allHistoryText.push(historyItems[i]["title"]);
allHistoryUrl.push(historyItems[i]["url"]);
}
// some functions
findLastEpisodeLinks();
displayAll(finalAllSeries);
});