Skip to content

Instantly share code, notes, and snippets.

@jkeam
Last active February 19, 2016 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkeam/09d1fd2094b4bca666a3 to your computer and use it in GitHub Desktop.
Save jkeam/09d1fd2094b4bca666a3 to your computer and use it in GitHub Desktop.
Promises
'use strict';
const http = require('https');
function docs() {
console.log('The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn\'t completed yet, but is expected in the future.');
console.log("pending: initial state, not fulfilled or rejected.\n fulfilled: meaning that the operation completed successfully.\n rejected: meaning that the operation failed.");
console.log('Great notes from Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise');
}
function takesLongTime(url, resolve, reject) {
const callback = (response) => {
let str = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
str += chunk;
});
response.on('end', () => {
resolve(str.trim());
});
}
const req = http.get(url, callback);
req.end();
req.on('error', (e) => {
reject(e);
});
}
function doStuff() {
return new Promise((resolve, reject) => {
takesLongTime('https://www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new', resolve, reject);
});
}
function doBadStuff() {
return new Promise((resolve, reject) => {
takesLongTime('https://wont_work_at_all', resolve, reject);
});
}
//success
doStuff().then((randomNum) => {
console.log(`My random number: ${randomNum}`);
}).catch((err) => {
console.error(`Oh noes!: ${err}. I will never be called!`);
});
//failure
doBadStuff().then((randomNum) => {
console.log(`My randomNum: ${randomNum}. I will never be called!`);
}).catch((err) => {
console.error(`Oh noes!: ${err}`);
});
//race
const a1 = doStuff();
const a2 = doStuff();
const a3 = doStuff();
Promise.race([a1, a2, a3]).then((randomNum) => {
console.log(`Race: ${randomNum}`);
});
//all
const b1 = doStuff();
const b2 = doStuff();
const b3 = doStuff();
Promise.all([b1, b2, b3]).then((randomNums) => {
console.log(`All: ${randomNums.join(', ')}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment