Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Last active March 4, 2021 17:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjamundx/3f11b59dce694552110aebfd69e2a2fe to your computer and use it in GitHub Desktop.
Save xjamundx/3f11b59dce694552110aebfd69e2a2fe to your computer and use it in GitHub Desktop.
Promise Anti-Patterns

https://github.paypal.com/shsreedharan/FEUI/blob/SREMMTWO-780/mm2-alert-auditor/jobs/CertExAuditor.js#L26

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

@Dorpaxio
Copy link

Dorpaxio commented Mar 4, 2021

Unless getPhoto returns a Promised URL...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment