javascript - vanilla JS函数中的回调并不总是有效?
问题描述
我编写了一个小的 vanilla JS 函数来利用 XMLHttpRequest 对象。我有一个回调要返回,但由于某种原因,我只能让回调在onreadystatechange
函数上工作,我需要它在我的ontimeout
和onerror
......
我的功能:
function makeHttpRequest (type, url, timeout, callback) {
const xhr = new XMLHttpRequest()
xhr.open(type, url, true)
xhr.timeout = timeout
xhr.ontimeout = () => {
callback.apply('timeout error')
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.response != null) {
callback.apply(xhr)
}
}
xhr.onerror = () => {
callback.apply('generic error')
}
xhr.send()
}
我如何使用该功能:
makeHttpRequest('GET', url, timeout, function() {
const res = this.response != '' ? this.response : JSON.stringify({})
// ...
})
this.response
用于超时和错误时不包含任何内容。
解决方案
该apply
方法将函数的this
参数设置为其第一个参数。当发生超时或错误时,您可以像这样调用 apply:
callback.apply('timeout error');
因此,该this
值是一个字符串。如果您在javascript strings 的文档中,您会看到一个String
对象没有.response
属性。这就是为什么'timeout error'.response
不包含任何东西(它是undefined
)。
如果要this.response
包含错误消息,请不要将字符串传递为this
. 而是将其传递为.response
:
let error = {
response: 'timeout error'
}
callback.apply(error)
或者更简单地说:
callback.apply({ response: 'timeout error' })
推荐阅读
- python-3.x - 如何在 GPU 上使用 Python 更改 Pixeldata
- c# - 执行SSIS脚本任务后,excel进程在后台运行
- java - 如果在 sprinframework jdbc 中自动生成 id,如何插入冲突
- jquery - Ajax响应后如何从Controller获取“ViewBag”值到js文件
- matlab - 如何使matlab按顺序读取文件夹内具有相似文件名的文件?
- asp.net-core - 使用 dacpac 代码 (asp .net core) 在 Visual Studio 中发布项目
- android - android项目中V8 7.4.288.22版本库的交叉编译失败
- gradle - 运行 Gradle 时出错 [无法解析配置的所有工件]
- php - 将一组重写规则从php导出到apache:这可能吗?
- php - 如何从 5.6 更新 Google Compute Engine 中的 PHP?