diff --git a/lib/promise.js b/lib/promise.js index f0560962..6fc2f7c1 100644 --- a/lib/promise.js +++ b/lib/promise.js @@ -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); }; diff --git a/promise-test.js b/promise-test.js index d7d441b5..6c98e949 100644 --- a/promise-test.js +++ b/promise-test.js @@ -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); \ No newline at end of file + 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); +