Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/9110935 to your computer and use it in GitHub Desktop.
Save getify/9110935 to your computer and use it in GitHub Desktop.
promise sync vs async?
// Hey, what gives here? This is weird and unexpected.
// Why is the promise factory called synchronously, when
// all the other steps resolve async? For consistency,
// one would expect them all to be async.
var p = new Promise(function(resolve,reject){
console.log("what");
resolve();
});
p.then(function(){
console.log("here?");
});
console.log("happened");
// got: what, happened, here?
// expected: happened, what, here?
@tooshel
Copy link

tooshel commented Feb 21, 2014

Seems that is the norm. All the libraries listed here do the same.

http://www.promisejs.org/implementations/

@jtdevos
Copy link

jtdevos commented Feb 21, 2014

edit: fixing some js typos

The trite/lame answer for "why is the promise constructor synchronous?" is "because the spec says so". Here's my guesses for the rationale behind the spec:

  • Increased flexibility. Promises often perform async tasks but they don't necessarily need to do so.
  • Safer initialization - the initializer may rely upon state that is altered in subsequent (synchronous)javascript statements. Consider the following (dumb) example:
var person = getPersonRecord();
var p = new Promise(function(resolve, reject){
    var grade = lookupStudentGrades(person.id);
    if(p.id) {
      displayGradeOnPage(grade);
      resolve();
    } else {
      reject();
    }
});
//... other statements...

person.id =  null;  

If the promise constructor was async, the promise would ultimately reject because one of the closures it uses was altered before the constructor had a chance to execute.

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