Merge pull request #412 from sjones6/thenify_val

Alternative promiseified `val`
This commit is contained in:
Mark Nadal 2017-09-18 13:25:58 -07:00 committed by GitHub
commit cfdb5f8f0b
2 changed files with 36 additions and 12 deletions

View File

@ -1,10 +1,10 @@
var Gun = Gun || require('../gun');
Gun.chain.promise = function(field) {
var gun = this;
return new Promise(function(resolve, reject) {
gun.get(field).val(function(node, key) {
resolve(node, key);
Gun.chain.promise = function(cb) {
var gun = this, cb = cb || function(ctx) { return ctx };
return (new Promise(function(res, rej) {
gun.val(function(node, key) {
res({val: node, key: key, gun: gun});
});
});
})).then(cb);
};

View File

@ -3,18 +3,42 @@ require('./lib/promise');
var gun = new Gun();
gun.get('mark').put({
/* prep */
var mark = gun.get('mark').put({
name: 'mark'
})
var cat = gun.get('cat').put({
name: 'sylvester'
});
mark.get('boss').put(cat);
cat.get('slave').put(mark);
/* async/await syntax */
async function getField(field) {
var node = await gun.promise(field);
console.log(node);
var node = await gun.get(field).promise();
console.log({1: node.val});
return node;
};
setTimeout(async () => {
var mark = await getField('mark');
console.log(mark);
process.exit();
}, 100);
console.log({2: mark.val});
}, 100);
/* chained thens */
setTimeout(() => {
gun.get('mark')
.promise(ctx => {
console.log({a: ctx.val});
return mark.get('boss').promise();
})
.then(cat => {
console.log({b: cat.val});
return cat.gun.get('slave').promise();
})
.then(mark => {
console.log({c: mark.val});
process.exit();
});
}, 200);