node.js - `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()
的事件处理程序
很难理解上面两个代码的区别:(对象内部的
剂量不是函数?
为什么不起作用?resolve
new Promise
xhr.onload = resolve();
解决方案
xhr.onload = 解决()
在这里你调用了解析回调(注意括号),所以你基本上是在做:
xhr.onload = (resolve(xhr) 调用返回的值。
当您需要提供“onclick”功能时。所以在这里,当你调用 resolve 时,promise 会立即解决。并且没有按预期工作。
xhr.onload = () => {resolve(xhr)}
在这里,您提供了一个函数(在内部调用 resolve),因此它可以工作。
推荐阅读
- docker - Pomelo / Docker / MySQL - 无法连接到任何指定的 MySQL 主机
- php - Laravel - 在模型中引入 trix 字段
- php - 如何使用 PHP curl 方法格式化 POST 请求?
- powerbi-embedded - 如何收听选择视觉对象的事件?
- python - 如何在 Python 中使用 ConfigParser() 读取列表中的列表?
- python - 如何处理flask-socketio中的事件?
- javascript - 以漂亮的 HTML 格式显示 JSON
- java - 使用内置排序功能对二维数组进行排序
- c - 在makefile中使用ar(1)命令时将库提取到不同的路径
- python - 如何根据 python 中的多个标准连接两个数据框?