1.代码如下,我希望从seclect中返回请求成功后取得的结果,请求是异步的,有什么办法或者替代办法?2.function select(key,store) { // 怎么保证这个异步结果的返回...
var request3 = store.get(key);
request3.onerror = function(event) { console.log("Error : " + event.errorCode);
};
request3.onsuccess = function(event) { return event.target.result;
};
}
1 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
1.回调函数
function select(key,store, callback) { var request3 = store.get(key); request3.onerror = function(event) { console.log("Error : " + event.errorCode); }; request3.onsuccess = function(event) { callback(event.target.result); }; }// 调用select(key,store, function(result) { console.log(result) })
2.Promise
function select(key,store, onsuccess) { var request3 = store.get(key); return new Promise(function(resolve, reject) { request3.onerror = function(event) { reject(event); }; request3.onsuccess = function(event) { resolve(event.target.result); }; }) }// 调用select(key,store).then(function(result){ // success console.log(result) }, function(e){ // error console.log(e) })
3.Event
// 监听自定义事件window.addEventListener('selectSuccess', function(e){ console.log(e.result) })function select(key,store, onsuccess) { var request3 = store.get(key); request3.onerror = function(event) { console.log("Error : " + event.errorCode); }; request3.onsuccess = function(event) { // 触发事件 var myEvent = new Event('selectSuccess'); myEvent.result = event.target.result; window.dispatchEvent(myEvent); }; }
添加回答
举报
0/150
提交
取消