【发布时间】:2020-12-23 00:20:08
【问题描述】:
我正在使用 JS 进行 chrome 扩展。函数 chrome.history.search 是一个异步回调。由于它是异步的,因此我计划使用 promise 使其同步。我希望代码使用 chrome.history.search 将值分配给 url,然后将其推送到全局数组 lastEpisodeLink。还有另一个函数 findLastEpisodeLink 在多个标题上调用 findLastEpisode_helper。
我需要的输出序列是:
开始,
里面,
成功,
开始,
里面,
成功,...
但我得到的是:
开始,开始,里面,成功,里面,成功
当我在函数运行后检查数组 lastEpisodeLink 时,它显示不应该是空的。我该如何解决这个问题?
是的,我已经按照How do I return the response from an asynchronous call? 的答案进行了操作,但仍然没有解决它。如果您能帮助我修复此代码,那将非常有帮助。谢谢
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);
}
调用它的函数
function findLastEpisodeLinks() {
for(title in stringArray) { //psudo code
findLastEpisodeLink_helper(title);
}
}
调用它的函数如下,它本身就是一个异步回调,所有的调用都在这里完成。
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);
});
【问题讨论】:
-
Promise 是异步的。您究竟如何认为使用 Promise 会使其同步?
-
我该如何解决这个问题,你能帮忙
-
您可以在解析中传递 url,并且在成功时同样可以访问。它将解决空数组的问题。
-
是的,它确实填充了数组,但它由对象 promise{fulfield} 填充
标签: javascript asynchronous google-chrome-extension promise callback