Promises
Frontend Developer
Aries
ES6
require("request")
.get("http://www.google.com", function(err, response) {
console.log(response.body)
})
require("popsicle")
.get("http://www.google.com")
.then(function(response) {
console.log(response.body);
})
require("request")
.get("http://www.google.com", function(err, response) {
if (err) {
console.error(err);
} else {
require("fs")
.writeFile("google.html", response.body, function(err) {
if (err) {
console.error(err);
} else {
console.log("wrote file");
}
})
}
})
require("popsicle").get("http://www.google.com")
.then(function(response) {
return require("fs-promise").writeFile("google.html", response.body);
})
.then(function() {
console.log("wrote file");
})
.catch(function(err) {
console.log(err);
})
A Design Pattern
Native in JavaScript
Available in libraries
A promise can be in one of 3 states:
let promiseToClean = new Promise(function( resolve, reject) {
let isClean = true;
if (isClean) {
resolve('the room is Clean')
} else {
reject('the room is not clean')
}
})
Promise.then()
let promiseToClean = new Promise(function(resolve, reject) {
let isClean = true;
if (isClean) {
resolve("is clean")
} else {
reject("is not clean")
}
})
promiseToClean.then(function(value) {
console.log("the room is " + value)
}).catch(function() {
console.log('the room is' + value)
})
Promise.catch()
let cleanRoom = function() {
return new Promise(function(resolve, reject) {
resolve('Cleaned the Room\n')
})
};
let removeGarbage = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + 'Removed the garbage\n')
})
};
let winIcecream = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + 'Won Ice Cream\n')
})
};
cleanRoom().then(function(result) {
return removeGarbage(result);
}).then(function(result) {
return winIcecream(result);
}).then(function(result) {
console.log('finished!\n' + result);
})
Promise.all([])
Promise.all([cleanRoom(), removeGarbage(), winIcecream()]).then(function() {
console.log('all finished')
})
Promise.race([])
Promise.race([cleanRoom(), removeGarbage(), winIcecream()]).then(function() {
console.log('one of them is finished')
})
function(request, response) {
var user, notebook;
User.get(request.user)
.then(function(aUser) {
user = aUser;
return Notebook.get(user.notebook);
})
.then(function(aNotebook) {
notebook = aNotebook;
return doSomethingAsync(user, notebook);
})
.then(function(result) {
response.send(result)
})
.catch(function(err) {
response.send(err)
})
}