Skip to content

Instantly share code, notes, and snippets.

@getify
Created May 21, 2015 04:12
Show Gist options
  • Save getify/eb71c7cdc002397f1bea to your computer and use it in GitHub Desktop.
Save getify/eb71c7cdc002397f1bea to your computer and use it in GitHub Desktop.
Promises pop quiz: can you articulate the difference(s) between these two snippets?
function foo() {
return new Promise(function(resolve){
mayThrow();
resolve("foo");
});
}
function foo() {
return Promise.resolve().then(function(){
mayThrow();
return "foo";
});
}
@WaseemCake
Copy link

gistfile2.js --> The promise is not resolved and always goes into pending state. And also by definition , The Promise.resolve(value) method returns a Promise object that is resolved with the given value. Here , We are not providing the any value to the promise i.e., success, reject.

gistfile1.js --> Its actually goes ahead and creates an instance of the Promise with new. And hence, code gets executed till the end within the anonymous function.

@greim
Copy link

greim commented May 21, 2015

How about: mayThrow() runs synchronously in the first but not second. Maybe that's a nit-pick, but I can see how it could trip someone up in certain circumstances.

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