我如何宣传原生XHR?

Som*_*ens 167 javascript xmlhttprequest promise

我想在我的前端应用程序中使用(本机)promises来执行XHR请求,但没有庞大框架的所有tomfoolery.

我希望我的XHR返回的希望,但是,这并不工作(给我:Uncaught TypeError: Promise resolver undefined is not a function)

function makeXHRRequest (method, url, done) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.onload = function() { return new Promise().resolve(); };
  xhr.onerror = function() { return new Promise().reject(); };
  xhr.send();
}

makeXHRRequest('GET', 'http://example.com')
.then(function (datums) {
  console.log(datums);
});
Run Code Online (Sandbox Code Playgroud)

Som*_*ens 337

我假设你知道如何制作原生的XHR请求(你可以在这里这里一下)

由于任何支持本机承诺的浏览器也会支持xhr.onload,我们可以跳过所有的onReadyStateChangetomfoolery.让我们退一步,从使用回调的基本XHR请求函数开始:

function makeRequest (method, url, done) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.onload = function () {
    done(null, xhr.response);
  };
  xhr.onerror = function () {
    done(xhr.response);
  };
  xhr.send();
}

// And we'd call it as such:

makeRequest('GET', 'http://example.com', function (err, datums) {
  if (err) { throw err; }
  console.log(datums);
});
Run Code Online (Sandbox Code Playgroud)

欢呼!这不涉及任何非常复杂的事情(如自定义标题或POST数据),但足以让我们前进.

承诺构造函数

我们可以这样构建一个承诺:

new Promise(function (resolve, reject) {
  // Do some Async stuff
  // call resolve if it succeeded
  // reject if it failed
});
Run Code Online (Sandbox Code Playgroud)

该承诺的构造采用了将传递两个参数的函数(让我们称他们为resolvereject).您可以将这些视为回调,一个用于成功,一个用于失败.示例很棒,让我们makeRequest用这个构造函数更新:

function makeRequest (method, url) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    xhr.send();
  });
}

// Example:

makeRequest('GET', 'http://example.com')
.then(function (datums) {
  console.log(datums);
})
.catch(function (err) {
  console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)

现在我们可以利用promises的功能,链接多个XHR调用(并且.catch会在任一调用时触发错误):

makeRequest('GET', 'http://example.com')
.then(function (datums) {
  return makeRequest('GET', datums.url);
})
.then(function (moreDatums) {
  console.log(moreDatums);
})
.catch(function (err) {
  console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)

我们可以进一步改进这一点,添加POST/PUT参数和自定义标题.让我们使用选项对象而不是多个参数,签名:

{
  method: String,
  url: String,
  params: String | Object,
  headers: Object
}
Run Code Online (Sandbox Code Playgroud)

makeRequest 现在看起来像这样:

function makeRequest (opts) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(opts.method, opts.url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    if (opts.headers) {
      Object.keys(opts.headers).forEach(function (key) {
        xhr.setRequestHeader(key, opts.headers[key]);
      });
    }
    var params = opts.params;
    // We'll need to stringify if we've been given an object
    // If we have a string, this is skipped.
    if (params && typeof params === 'object') {
      params = Object.keys(params).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
      }).join('&');
    }
    xhr.send(params);
  });
}

// Headers and params are optional
makeRequest({
  method: 'GET',
  url: 'http://example.com'
})
.then(function (datums) {
  return makeRequest({
    method: 'POST',
    url: datums.url,
    params: {
      score: 9001
    },
    headers: {
      'X-Subliminal-Message': 'Upvote-this-answer'
    }
  });
})
.catch(function (err) {
  console.error('Augh, there was an error!', err.statusText);
});
Run Code Online (Sandbox Code Playgroud)

MDN可以找到更全面的方法.

或者,您可以使用fetch API(polyfill).

  • 拒绝返回新的错误会更好吗? (4认同)
  • 您可能还想为`responseType`,身份验证,凭据,`timeout`添加选项...而``params`对象应该支持blob/bufferviews和`FormData`实例 (3认同)
  • 除了一件事外,这段代码似乎可以像宣传的那样工作。我希望将参数传递给GET请求的正确方法是通过xhr.send(params)。但是,GET请求将忽略发送到send()方法的任何值。相反,它们只需要是URL本身上的查询字符串参数。因此,对于上述方法,如果要将“ params”参数应用于GET请求,则需要修改例程以识别GET与POST,然后有条件地将这些值附加到传递给xhr的URL 。打开()。 (2认同)

Pel*_*leg 48

这可以像下面的代码一样简单.

请记住,此代码仅在reject调用时触发回调onerror(仅限网络错误),而不是在HTTP状态代码表示错误时触发.这也将排除所有其他例外情况.处理这些应该取决于你,IMO.

另外,建议reject使用实例Error而不是事件本身来调用回调,但为了简单起见,我保持原样.

function request(method, url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = resolve;
        xhr.onerror = reject;
        xhr.send();
    });
}
Run Code Online (Sandbox Code Playgroud)

并调用它可能是这样的:

request('GET', 'http://google.com')
    .then(function (e) {
        console.log(e.target.response);
    }, function (e) {
        // handle errors
    });
Run Code Online (Sandbox Code Playgroud)

  • @MadaraUchiha我想这是它的tl; dr版本.它给了OP一个他们问题的答案而且只有那个. (14认同)
  • 我喜欢这个答案,因为它提供了非常简单的代码,可以立即使用它来回答问题. (6认同)
  • @crl 就像在常规 XHR 中一样:`xhr.send(requestBody)` (2认同)

mic*_*oo8 9

对于现在搜索此内容的任何人,您都可以使用获取功能.它有一些非常好的支持.

我首先使用了@ SomeKittens的答案,但随后发现fetch它对我来说是开箱即用的:)

  • 旧版浏览器不支持 `fetch` 功能,但 [GitHub 发布了一个 polyfill](https://github.com/github/fetch)。 (2认同)
  • 我不推荐 `fetch`,因为它还不支持取消。 (2认同)
  • Fetch API 的规范现在提供取消。到目前为止,支持已在 Firefox 57 https://bugzilla.mozilla.org/show_bug.cgi?id=1378342 和 Edge 16 中提供。演示:https://fetch-abort-demo-edge.glitch.me/ &amp; https: //mdn.github.io/dom-examples/abort-api/。还有开放的 Chrome 和 Webkit 功能错误 https://bugs.chromium.org/p/chromium/issues/detail?id=750599 &amp; https://bugs.webkit.org/show_bug.cgi?id=174980。操作方法:https://developers.google.com/web/updates/2017/09/abortable-fetch &amp; https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#Examples (2认同)

jpm*_*c26 7

我认为通过不创建对象,我们可以使最佳答案更加灵活和可重用XMLHttpRequest.这样做的唯一好处是我们不必自己编写2行或3行代码,并且它具有取消对API的许多功能(如设置标题)的巨大缺点.它还从应该处理响应的代码中隐藏原始对象的属性(对于成功和错误).因此,我们可以通过接受XMLHttpRequest对象作为输入并将其作为结果传递来制作更灵活,更广泛适用的函数.

此函数将任意XMLHttpRequest对象转换为promise,默认情况下将非200状态代码视为错误:

function promiseResponse(xhr, failNon2xx = true) {
    return new Promise(function (resolve, reject) {
        // Note that when we call reject, we pass an object
        // with the request as a property. This makes it easy for
        // catch blocks to distinguish errors arising here
        // from errors arising elsewhere. Suggestions on a 
        // cleaner way to allow that are welcome.
        xhr.onload = function () {
            if (failNon2xx && (xhr.status < 200 || xhr.status >= 300)) {
                reject({request: xhr});
            } else {
                resolve(xhr);
            }
        };
        xhr.onerror = function () {
            reject({request: xhr});
        };
        xhr.send();
    });
}
Run Code Online (Sandbox Code Playgroud)

此函数非常自然地适用于Promises 链,而不会牺牲XMLHttpRequestAPI 的灵活性:

Promise.resolve()
.then(function() {
    // We make this a separate function to avoid
    // polluting the calling scope.
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://stackoverflow.com/');
    return xhr;
})
.then(promiseResponse)
.then(function(request) {
    console.log('Success');
    console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)

catch上面省略了以保持示例代码更简单.你应该总是有一个,当然我们可以:

Promise.resolve()
.then(function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://stackoverflow.com/doesnotexist');
    return xhr;
})
.then(promiseResponse)
.catch(function(err) {
    console.log('Error');
    if (err.hasOwnProperty('request')) {
        console.error(err.request.status + ' ' + err.request.statusText);
    }
    else {
        console.error(err);
    }
});
Run Code Online (Sandbox Code Playgroud)

禁用HTTP状态代码处理不需要对代码进行太多更改:

Promise.resolve()
.then(function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://stackoverflow.com/doesnotexist');
    return xhr;
})
.then(function(xhr) { return promiseResponse(xhr, false); })
.then(function(request) {
    console.log('Done');
    console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)

我们的调用代码更长,但从概念上讲,理解正在发生的事情仍然很简单.我们不必为了支持其功能而重建整个Web请求API.

我们可以添加一些便利功能来整理我们的代码:

function makeSimpleGet(url) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    return xhr;
}

function promiseResponseAnyCode(xhr) {
    return promiseResponse(xhr, false);
}
Run Code Online (Sandbox Code Playgroud)

然后我们的代码变成:

Promise.resolve(makeSimpleGet('https://stackoverflow.com/doesnotexist'))
.then(promiseResponseAnyCode)
.then(function(request) {
    console.log('Done');
    console.log(request.status + ' ' + request.statusText);
});
Run Code Online (Sandbox Code Playgroud)


t.a*_*mal 5

我认为jpmc26的答案非常接近完美。但是,它有一些缺点:

  1. 它只公开xhr请求,直到最后一刻。这不允许POST-requests设置请求正文。
  2. 关键send调用隐藏在函数内部,因此很难阅读。
  3. 实际提出请求时,它引入了很多样板。

猴子修补xhr对象可解决以下问题:

function promisify(xhr, failNon2xx=true) {
    const oldSend = xhr.send;
    xhr.send = function() {
        const xhrArguments = arguments;
        return new Promise(function (resolve, reject) {
            // Note that when we call reject, we pass an object
            // with the request as a property. This makes it easy for
            // catch blocks to distinguish errors arising here
            // from errors arising elsewhere. Suggestions on a 
            // cleaner way to allow that are welcome.
            xhr.onload = function () {
                if (failNon2xx && (xhr.status < 200 || xhr.status >= 300)) {
                    reject({request: xhr});
                } else {
                    resolve(xhr);
                }
            };
            xhr.onerror = function () {
                reject({request: xhr});
            };
            oldSend.apply(xhr, xhrArguments);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

现在的用法很简单:

let xhr = new XMLHttpRequest()
promisify(xhr);
xhr.open('POST', 'url')
xhr.setRequestHeader('Some-Header', 'Some-Value')

xhr.send(resource).
    then(() => alert('All done.'),
         () => alert('An error occured.'));
Run Code Online (Sandbox Code Playgroud)

当然,这带来了另一个缺点:猴子修补确实会损害性能。但是,假设用户主要在等待xhr的结果,请求本身花费的时间量比建立呼叫长且xhr请求不经常发送,则这应该不是问题。

PS:当然,如果要针对现代浏览器,请使用fetch!

PPS:在评论中已经指出,此方法更改了可能令人困惑的标准API。为了更好的说明,可以在xhr对象上修补另一种方法sendAndGetPromise()