`xhr.onload = ()=>{resolve();}` 和 `xhr.onload = resolve();` 之间的区别

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();
   })
}

上面的代码运行良好

但是

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

但此代码无效。

因为 onload() 是一个事件处理程序,它为特定事件
设置了一个 函数 很难理解上面两个代码的区别:(
new Promise 对象里面的 dose resolve 不是函数?
为什么 xhr.onload = resolve(); 不起作用?

xhr.onload = resolve()

在这里你调用了 resolve 回调(注意括号),所以你基本上是在做:

xhr.onload =(调用 resolve(xhr) 返回的值。

当您需要向 'onclick' 提供功能时。 所以在这里,当你调用 resolve 时,promise 会立即 resolve。并且没有按预期工作。

xhr.onload = () => {解析(xhr)}

这里你提供了一个函数(在内部调用 resolve),所以它可以工作。