co_lin
co_lin

Reputation: 135

Difference between `xhr.onload = ()=>{resolve();}` and `xhr.onload = resolve();`

function foo(){
   return new Promise((resolve,reject)=>{
      const xhr = new XMLHttpRequest();
      xhr.open(method,url);
      xhr.onload = ()=>{ resolve(xhr); };
      xhr.send();
   })
}

Code above works well

but

function foo(){
   return new Promise((resolve,reject)=>{
      const xhr = new XMLHttpRequest();
      xhr.open(method,url);
      xhr.onload = resolve(xhr);
      xhr.send();
   })
}

But this code won't works.

As onload() is a event handler that setting a function for certain event
Its hard to understand the difference of both code above :(
Dose resolve inside the new Promise object is not a function?
Why does xhr.onload = resolve(); doesn't work?

Upvotes: 1

Views: 149

Answers (1)

Nike Lepz
Nike Lepz

Reputation: 543

xhr.onload = resolve()

Here you're calling the resolve callback(notice the parenthesis), so you're basically doing:

xhr.onload = (value returned by the call to resolve(xhr).

when you need to provide a function to 'onclick'. So here the promise resolves immediately as you are calling resolve. And doesn't work as expected.

xhr.onload = () => {resolve(xhr)}

Here you're providing a function(which calls resolve inside), so it works.

Upvotes: 2

Related Questions