Last active
August 29, 2015 13:56
-
-
Save getify/9110935 to your computer and use it in GitHub Desktop.
promise sync vs async?
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
// 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? |
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
Seems that is the norm. All the libraries listed here do the same.
http://www.promisejs.org/implementations/