Skip to content

Instantly share code, notes, and snippets.

@MikeyBurkman
Last active June 10, 2016 14:06
Show Gist options
  • Save MikeyBurkman/cfb18e545d52a1360c1fa3d6e2d8abee to your computer and use it in GitHub Desktop.
Save MikeyBurkman/cfb18e545d52a1360c1fa3d6e2d8abee to your computer and use it in GitHub Desktop.
Promises Demonstration
#! /usr/bin/env cecil
var Promise = include('bluebird', '3.3.3');
var request = include('request-promise', '3.0.0');
var fs = Promise.promisifyAll(require('fs'));
/////////////
Promise.all([
basicPromise(),
// nestedPromises(),
// uncaughtExceptions(),
// multipleThens(),
// errorHandling(),
// delayedResolution(),
// parallelRequests(),
// parallelRequestsMap(),
// sequentialProcessing(),
// limitConcurrency(),
// promiseSpread(),
// promiseTimeout(),
// promiseWaterfall()
])
// .then(function() {
// console.log('Finished');
// });
/////////////
function basicPromise() {
var fn = function(x) {
return new Promise(function(resolve, reject) {
if (x > 0) {
resolve(x);
} else {
reject(new Error('X is negative'));
}
});
}
fn(5).then(function(result) {
console.log('Result = ', result);
});
fn(-4).then(function(result) {
console.log('We should not see this');
})
.catch(function(err) {
console.log('Got an error', err);
});
}
function nestedPromises() {
var f1 = function(n) {
return Promise.delay(100)
.then(function() {
return n + 5;
});
}
var f2 = function(x) {
return Promise.delay(200)
.then(function() {
return x * 2;
})
}
return Promise.resolve()
.then(function() {
return f1(16)
})
.then(f2)
.then(console.log);
}
function uncaughtExceptions() {
var fn = function(x) {
return x.ticketId.toString();
}
return Promise.resolve()
.then(function() {
return fn({ticketID: '123'});
})
.then(function(id) {
console.log('ID = ' , id);
})
// .catch(function(err) {
// console.log('Oh noes error', err.stack);
// });
}
function multipleThens() {
var promise = Promise.delay(500)
.then(function() {
console.log('Promise has resolved');
return 'foo';
});
promise.then(function(result) {
console.log('Result = ', result);
});
promise.then(function(resultAgain) {
console.log('Got the result again: ', resultAgain);
});
}
// Demonstrate error handling in bluebird
function errorHandling() {
function execute(x) {
if (x === 0) {
throw new Error('ZERO');
}
if (x < 0) {
throw new Error('NEGATIVE');
}
return x/5;
}
return Promise.resolve()
.then(function() {
return execute(20);
})
.then(function(data) {
console.log('First data: ', data);
})
.then(function() {
return execute(0);
})
.catch({message: 'ZERO'}, function(err) {
console.log('Got a zero, continuing on');
return 'this is alright';
})
.then(function(data) {
console.log('Data from previous result: ', data);
return execute(-1);
})
.catch({message: 'ZERO'}, function(err) {
console.log('Got a zero AGAIN?');
return 'bad bad bad';
})
.catch(function(err) {
console.log('Got a different error', err);
return 'ok'
})
.then(function(data) {
console.log('Final result: ', data);
});
}
// Demonstrate that a promise doesn't need to have a 'then' listener on it
// when it's resolved
function delayedResolution() {
var promise1 = Promise.resolve('foo');
setTimeout(function() {
promise1.then(function(result) {
console.log('Result = ', result);
});
}, 300);
return promise1;
}
// Read several URLs in parallel
// We can actually access the value of the first one before the other two have finished
function parallelRequests() {
var urls = [
'http://www.google.com',
'http://www.redhat.com',
'http://www.github.com'
];
function execute(url) {
var startTime = new Date();
return request(url)
.then(function(data) {
console.log('Received data for ', url, ' after ', new Date() - startTime);
return data;
});
}
var promises = urls.map(execute);
promises[0].then(function(google) {
console.log('Google = ', google.substr(0, 10));
});
return Promise.all(promises)
.then(function(results) {
console.log(results.map(function(html) {
return html.substr(0, 10);
}));
});
}
//// Bluebird-specific examples below
function parallelRequestsMap() {
var requests = {
google: request('http://www.google.com'),
redhat: request('http://www.redhat.com'),
github: request('http://www.github.com')
};
return Promise.props(requests)
.then(function(results) {
console.log('Google = ', results.google.substr(0, 20));
console.log('Redhat = ', results.redhat.substr(0, 20));
console.log('Github = ', results.github.substr(0, 20));
});
}
function sequentialProcessing() {
var urls = [
'http://www.google.com',
'http://www.redhat.com',
'http://www.github.com'
];
function execute(url) {
console.log('Getting url: ', url);
return request(url)
.then(function(data) {
console.log('Got data for url: ', url);
});
}
return Promise.mapSeries(urls, execute);
}
function limitConcurrency() {
var data = [1, 2, 3, 4, 5, 6];
function execute(x) {
var delay = Math.ceil(Math.random() * 1000) + 500
console.log('Executing', x, '(Will take ', delay, 'ms)');
return Promise.delay(delay)
.then(function() {
console.log('Finished processing', x);
return x * x;
});
}
return Promise.map(data, execute, {concurrency: 2})
.then(function(results) {
console.log('Results = ', results);
});
}
// Read a file and a URL in parallel and logs the results
function promiseSpread() {
var file = fs.readFileAsync(__filename, 'utf8');
var html = request('http://www.redhat.com');
return Promise.all([file, html])
.spread(function(fileResult, htmlResult) {
console.log('File = ', fileResult.substr(0, 50));
console.log('\n=====\n');
console.log('Html = ', htmlResult.substr(0, 50));
});
}
function promiseTimeout() {
var promise1 = Promise.delay(2000).then(function() {
console.log('Promise1 resolved');
});
return promise1.timeout(500)
.catch(Promise.TimeoutError, function(err) {
console.log('Got a timeout error', err);
})
.then(function() {
console.log('Finished timeout test');
});
}
// Passing the results of each promise to the next promise, data coming from an array
function promiseWaterfall() {
var data = [1, 2, 3, 4];
function execute(previousResult, currentValue) {
return Promise.delay(300).then(function() {
return previousResult + currentValue;
});
}
return Promise.reduce(data, execute)
.then(function(result) {
console.log('Final result: ', result);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment