Javascript 普通JS函数中的回调不';你不总是工作吗?
我已经编写了一个小型的vanilla JS函数来使用XMLHttpRequest对象。我有一个回调要返回,但由于某种原因,我只能让回调用于Javascript 普通JS函数中的回调不';你不总是工作吗?,javascript,function,callback,xmlhttprequest,Javascript,Function,Callback,Xmlhttprequest,我已经编写了一个小型的vanilla JS函数来使用XMLHttpRequest对象。我有一个回调要返回,但由于某种原因,我只能让回调用于onreadystatechange函数,我需要它来处理我的ontimeout和onerror 我的职能: 函数makeHttpRequest(类型、url、超时、回调){ const xhr=new XMLHttpRequest() xhr.open(类型、url、true) xhr.timeout=超时 xhr.ontimeout=()=>{ callba
onreadystatechange
函数,我需要它来处理我的ontimeout
和onerror
我的职能:
函数makeHttpRequest(类型、url、超时、回调){
const xhr=new XMLHttpRequest()
xhr.open(类型、url、true)
xhr.timeout=超时
xhr.ontimeout=()=>{
callback.apply('超时错误')
}
xhr.onreadystatechange=()=>{
if(xhr.readyState==4&&xhr.response!=null){
callback.apply(xhr)
}
}
xhr.onerror=()=>{
callback.apply('generic error')
}
xhr.send()
}
我如何使用该函数:
makeHttpRequest('GET',url,超时,函数(){
const res=this.response!=''?this.response:JSON.stringify({})
// ...
})
this.response
在超时和出错时不包含任何内容。应用方法将函数的this
参数设置为其第一个参数。当发生超时或错误时,按如下方式调用apply:
callback.apply('timeout error');
因此,这个
值是一个字符串。如果位于,您将看到字符串
对象没有.response
属性。这就是为什么“超时错误”。响应不包含任何内容(它是未定义的)
如果希望this.response
包含错误消息,则不要将字符串作为this
传递。而是将其作为传递。响应:
let error = {
response: 'timeout error'
}
callback.apply(error)
或者更简单地说:
callback.apply({ response: 'timeout error' })
嗯,取决于错误,可能没有响应?您还期望什么?您不应该使用回调。应用。你知道这个
关键字是如何工作的吗?