Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async & Performance Chapter 3, Promises Where does the async execution happen in a Promise? #1015

Closed
Cerebrum2 opened this issue Apr 23, 2017 · 4 comments

Comments

@Cerebrum2
Copy link

Cerebrum2 commented Apr 23, 2017

The following code snippet is from Async & Performance Chapter 3.

I think the comment // start doing something that could take a while is misleading:

function foo(x) {
	// start doing something that could take a while

	// construct and return a promise
	return new Promise( function(resolve,reject){
		// eventually, call `resolve(..)` or `reject(..)`,
		// which are the resolution callbacks for
		// the promise.
	} );
}

If I understood correctly the async code should be inside the function passed to the Promise, no? So the following would be more accurate:

function foo(x) {
	// construct and return a promise
	return new Promise( function(resolve,reject){
                // start doing something that could take a while
                // then foo returns the newly created Promise
		// eventually, call `resolve(..)` or `reject(..)`,
		// which are the resolution callbacks for
		// the promise.
	} );
}
@Fov6363
Copy link

Fov6363 commented May 4, 2017

you are right;
function test_1() { console.log(1`);

return new Promise(function (resolve,reject) {
    console.log(`2`);

    return resolve(100);
})

}

test_1().then(val => console.log(val)); // 1 2 100`

@getify
Copy link
Owner

getify commented May 4, 2017

This is entirely valid and i've done it many times:

function foo() {
   ajax( "http://some. url", function(resp){
      resolve( resp );
   } );

   var resolve;

   return new Promise( function(res){
      resolve = res;
   } );
} 

@Cerebrum2
Copy link
Author

Cerebrum2 commented May 15, 2017

@getify
Valid yes, but why not simplify?

function foo() {
   return new Promise( function(resolve){
       ajax( "http://some. url", resolve);
   } );
} 

@getify
Copy link
Owner

getify commented Aug 15, 2017

There are various reasons you want to "extract" the resolve capability as my snippet showed. I'm only pointing out that it's orthogonal/irrelevant how the actual promise resolving logic ends up getting handled.

@getify getify closed this as completed Aug 15, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants