Created
August 15, 2014 15:18
-
-
Save redgeoff/3e7a481c019c6be01017 to your computer and use it in GitHub Desktop.
pouchdb-bad-remove-promise-fix
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
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="//cdn.jsdelivr.net/pouchdb/2.2.3/pouchdb.min.js"></script> | |
</head> | |
<body> | |
<script> | |
var db = new PouchDB('tasks'); | |
function saveTask() { | |
return db.post({ title: 'take out trash' }); | |
} | |
function getAndRemove(id) { | |
return db.get(id).then(function (object) { | |
return db.remove(object).catch(function (err) { | |
console.log('error: ' + err); // isn't executed | |
}); | |
}).catch(function (err) { | |
console.log('error: ' + err); // isn't executed | |
}); | |
} | |
function allDocsPromise(opts) { | |
return new Promise(function (fulfill, reject) { | |
db.allDocs(opts, function (err, doc) { | |
if (err) { | |
reject(err); | |
} else { | |
fulfill(doc); | |
} | |
}); | |
}); | |
} | |
function purge() { | |
return allDocsPromise({include_docs: true}).then(function (doc) { | |
var promises = []; | |
doc.rows.forEach(function (el, i) { | |
promises.push(getAndRemove(el.doc._id)); | |
}); | |
return Promise.all(promises); | |
}); | |
} | |
function printAllDocs() { | |
return allDocsPromise({ include_docs: true }).then(function (doc) { | |
console.log(doc); | |
}); | |
} | |
saveTask().then(function () { | |
purge().then(function () { | |
printAllDocs(); // is empty as expected | |
setTimeout(function () { | |
printAllDocs(); // is empty as expected | |
}, 2000); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment