我正在尝试将IndexedDB改为承诺,但函数checkUrlLink不会返回任何值。我该如何解决这个承诺?
这是我的代码:
var promise = new Promise(function(resolve) {
return checkUrlLink(send_to_url, event);
}).then(function(url_link) {
console.log('URL LINK in promisse' + url_link);
return clients.openWindow(url_link);
});
function checkUrlLink(send_to_url, event) {
return new Promise((resolve,reject) => {
var request = indexedDB.open('db', 1);
var original_event = event;
request.onsuccess = function (event) {
//db = event.target.result;
var url_link = "url_link";
var store = request.result.transaction("uid", "readwrite").objectStore("uid");
var getRequest = store.get(url_link);
getRequest.onsuccess = function () {
var result = getRequest.result;
if (result) {
url_link = result;
//send_to_url(original_event,url_link);
resolve(url_link);
} else {
url_link_value = self.registration.scope;
store.add(url_link_value, url_link);
//send_to_url(original_event, url_link_value);
resolve(url_link_value);
}
};
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
var store = db.createObjectStore('url_link');
};
});
}
我正在服务工作者中执行此操作。
答案 0 :(得分:2)
你在这里使用Promise构造函数反模式
var promise = new Promise(function(resolve) {
return checkUrlLink(send_to_url, event);
}).then(function(url_link) {
console.log('URL LINK in promisse' + url_link);
return clients.openWindow(url_link);
});
即。你正在包装一个在new Promise
内返回一个promise的函数 - 没有必要这样做。但是,您也从不调用解决方案,因此该代码存在两个问题
以上代码只是
var promise = checkUrlLink(send_to_url, event)
.then(function(url_link) {
console.log('URL LINK in promisse' + url_link);
return clients.openWindow(url_link);
};
现在promise是一个将解析为clients.openWindow(url_link);