.promise() and .then() thanks to @sjones6 !

This commit is contained in:
Mark Nadal 2017-09-18 13:49:36 -07:00
parent cfdb5f8f0b
commit a02273521d
4 changed files with 17 additions and 55 deletions

View File

@ -1,10 +0,0 @@
var Gun = Gun || require('../gun');
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);
};

16
lib/then.js Normal file
View File

@ -0,0 +1,16 @@
var Gun = Gun || require('../gun');
Gun.chain.promise = function(cb) {
var gun = this, cb = cb || function(ctx) { return ctx };
return (new Promise(function(res, rej) {
gun.val(function(data, key){
res({put: data, get: key, gun: this});
});
})).then(cb);
};
Gun.chain.then = function(cb) {
return this.promise(function(res){
return cb? cb(res.put) : res.put;
});
};

View File

@ -1,6 +1,6 @@
{
"name": "gun",
"version": "0.8.5",
"version": "0.8.6",
"description": "Graph engine",
"main": "index.js",
"browser": "gun.min.js",

View File

@ -1,44 +0,0 @@
var Gun = require('./gun');
require('./lib/promise');
var gun = new Gun();
/* 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.get(field).promise();
console.log({1: node.val});
return node;
};
setTimeout(async () => {
var mark = await getField('mark');
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);