Don’t Mix the Async lib or Callbacks and Promises
// bad example
async.paralell([function(callback) {
getUserPhotos().then((data) => callback(null, data), callback)
}, function(callback) {
logClickToAnalytics().then((data) => callback(null, data)).catch(callback)
}], function(err, results) {
if (err) {
console.error('error', err)
} else {
console.log(results)
}
})
// good example
Promise.all([getUserPhotos(), logClickToAnalyatics()])
.then(results => console.log(results))
.catch(error => console.error('error', error))
Avoid nesting by returning a Promise
// bad example
fetch(url).then(function(user) {
getPhoto(user.id).then(function(url) {
updateThumbnail(url).then(function() {
logAnalytics('thumbnailUpdated');
});
});
});
// good example
fetch(url).then(function(user) {
return getPhoto(user.id);
}).then(function(url) {
return updateThumbnail(url);
}).then(function() {
return logAnalytics('thumbnailUpdated')
})
In general, re-return and re-throw
// bad example
getData(url).then(function(data) {
console.log(data);
}).then(function(data) {
console.log(data) // undefined
})
// good example
getData(url).then(function(data) {
console.log(data);
return data;
}).then(function(data) {
console.log(data) // yay!
})
Make Sure to Catch Errors (or return)
Essentially you either need to catch an error or return and let the error bubble up, don't ever ignore errors on purpose. You also may need to re-throw if you want the error to bubble.
// bad example
saveUser(userId).then(function() {
console.log('user saved')
})
// good example #1
saveUser(userId).then(function() {
console.log('user saved')
}).catch(function() {
console.log('user not saved')
})
// this is also ok because the error will bubble
// good example #2
return saveUser(userId).then(function() {
console.log('user saved')
})
// and if you want the error to bubble you can re-throw
// good example #3
return saveUser(userId).then(function() {
console.log('user saved')
}).catch(function(err) {
console.log('user not saved')
throw err
})
Also you can read this a few times to get some of these ideas explained in more detail: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
You meant broken example?
updateThumbnail
depends onurl
butgetPhoto
obviously returns something else...This one will work only in nested style (or if you repackage arguments and return values together).