Last active
November 17, 2017 19:59
-
-
Save smolin/557a37cd5f255dc4968f2904a24fb539 to your computer and use it in GitHub Desktop.
Promise patterns in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
After reading a lot of pages about Promises, this page finally started making sense for me. It's a looong read and quite advanced but there are some good nuggets that help clarify things: | |
https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html | |
#. Always end a promise compose chain with | |
catch(console.log.bind(console)) | |
#. Inside a .then() ALWAYS RETURN OR THROW never let it be 'undefined' | |
return another promise | |
return a synchronous value (or undefined) | |
throw a synchronous error | |
#. When composing, name your promises: | |
var x = request({ method: 'GET', url: 'icanhazip.com' }) | |
x.then(response => { dosomething(response); return this }) | |
x.catch(console.log.bind(console)) | |
# To indicate that order of op is not significant, compose with Promise.all: | |
var x = request({ method: 'GET', url: 'icanhazip.com' }) | |
var y = request({ method: 'GET', url: 'helloacm.com/api/fortune' }) | |
var z = Promise.all([x, y]) | |
z.then(response => { dosomething(response); return this }) | |
z.catch(console.log.bind(console)) | |
# This shows how to splice non-promise stuff into a promise pipe, thanks Fermi: | |
``` | |
const Promise = require('bluebird') | |
var options = ['. abcd. '] | |
function inner(options) {return options} | |
function transform(options) {return options.trim()} | |
function wrapper(options) { | |
return new Promise ( | |
resolve => { return resolve() } | |
) | |
.then( () => inner(options) ) | |
.then( data => transform(data)) | |
} | |
wrapper(options) | |
.then(response => console.log('done: ' + response)) | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment