Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Created June 30, 2015 00:19
Show Gist options
  • Save emersonbroga/1fc25bce61dd0035990a to your computer and use it in GitHub Desktop.
Save emersonbroga/1fc25bce61dd0035990a to your computer and use it in GitHub Desktop.
Is there a better way to work with promises and callback?

#Is there a better way to work with promises and callback?

synchronous programming pseudo example:

var result = doSomething();

var param = (result[x]) ? 'foo' : 'bar';

var otherResult = doSomethingElse(param);

var saveResult = saveSomething(otherResult);

return json(saveResult);

asynchronous programming callback pseudo example:

doSomething( function(err, result){
	var param = (result[x]) ? 'foo' : 'bar';
	doSomethingElse(param, function(err, otherResult){
		saveSomething(otherResult, function (err, saveResult){
			return json(saveResult);
		});
	});
});

###asynchronous programming promises pseudo example:

doSomething().then(function(result){
	var param = (result[x]) ? 'foo' : 'bar';
	doSomethingElse(param).then(function(otherResult){
		saveSomething(otherResult).then(function(saveResult){
			return json(saveResult);
		}, function(error){

		});
	}, function(error){

	});
}, function(error){
	
});
@formula1
Copy link

Your second example is bad. You can return a promise within a promise.

doSomething().then(function(result){
    var param = (result[x]) ? 'foo' : 'bar';
    return doSomethingElse(param);
}).then(function(otherResult){
  return saveSomething(otherResult);
}).then(function(saveResult){
  return json(saveResult);
}).catch(function(e){
  //You have an error
});


var promiseGenerator = function(value){
  return new Promise(function(res,rej){
    setTimeout(function(){  res(value+"b") },100);
  });
};

var asyncCallback = function(value,next){ 
  setTimeout(function(){  next(void 0,value+"c") },100);
};

new Promise(function(good,bad){
  good("a");
}).then(function(value){
  return promiseGenerator(value);
}).then(function(value,good,bad){
  return new Promise(function(good,bad){
    asyncCallback(value,function(e,newValue){
      if(e) return bad(e);
      good(newValue)
    })
  });
}).then(function(value){
  console.log(value);
  throw value;
}).catch(function(e){
  throw e
});

So it definitely avoids callback hell. There are certian cases however that callback hell might sneak into promises, usually when asynchronously waiting for multiple functions and or other race conditions. However, All callbacks can end. There are other ways also to keep things pretty.

https://github.com/caolan/async
https://github.com/tj/co

amoung them

It can be awefuly ugly, but thats a sacrifice made for lack of threading or inherent async handling like Go

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