Created
September 21, 2016 13:20
-
-
Save dfahlander/6fa1ef4949da6d6f63c1500f24436814 to your computer and use it in GitHub Desktop.
Testing Native Promise compatibility with indexedDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<script src="https://unpkg.com/dexie/dist/dexie.js"></script> | |
<script> | |
const log = txt => console.log(txt);//document.writeln(`${txt}<br/>`); | |
log (`Hello world!`); | |
let db = new Dexie ('db'); | |
db.version(1).stores({ | |
friends: '++id,name,age' | |
}); | |
db.on('populate', ()=>{ | |
db.friends.add({name: "Foo", age: 37}); | |
db.friends.add({name: "Bar", age: 42}); | |
}); | |
db.delete().then(()=>{ | |
log(`Opening db`); | |
return db.open(); | |
}).then(()=>{ | |
log(`db opened`); | |
let idb = db.backendDB(); | |
let tx = idb.transaction('friends', 'readwrite'); | |
let store = tx.objectStore('friends'); | |
return p(()=>store.get(1)).then(friend=>{ | |
log(`Got: ${friend.name}`); | |
return p(()=>store.get(2)); | |
}).then(friend => { | |
log(`Got: ${friend.name}`); | |
return Promise.resolve().then(()=>Promise.resolve()).then(()=>Promise.resolve()); | |
}).then(() => { | |
return p(()=>store.add({name: "Another friend", age: 77})); | |
}).then(id => { | |
log(`Got another friend with id ${id}`); | |
return p(()=>store.get(id)); | |
}).then(friend => { | |
log(`Got the value of the other friend: '${friend.name}'`); | |
}).catch(err => log(`Error: ${err}`)); | |
}).catch (err => log(`Error: ${err.stack || err}`)); | |
function p (doer) { | |
return new Promise((resolve, reject) => { | |
let req = doer(); | |
req.onsuccess = ev => resolve(ev.target.result); | |
req.onerror = ev => reject(ev.target.error); | |
}); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment