首页 > 解决方案 > `xhr.onload = ()=>{resolve();}` 和 `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()的事件处理程序 很难理解上面两个代码的区别:(对象内部的 剂量不是函数? 为什么不起作用?

resolvenew Promise
xhr.onload = resolve();

标签: node.jsajaxpromisexmlhttprequest

解决方案


xhr.onload = 解决()

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

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

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

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

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


推荐阅读