首页 > 解决方案 > vanilla JS函数中的回调并不总是有效?

问题描述

我编写了一个小的 vanilla JS 函数来利用 XMLHttpRequest 对象。我有一个回调要返回,但由于某种原因,我只能让回调在onreadystatechange函数上工作,我需要它在我的ontimeoutonerror......

我的功能:

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用于超时和错误时不包含任何内容。

标签: javascriptfunctioncallbackxmlhttprequest

解决方案


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' })

推荐阅读