javascript - 我应该在 promise 中调用 XMLHttpRequest async 吗?

标签 javascript promise xmlhttprequest

<分区>

我在 promise 中使用基本的 XMLHttpRequest。由于 promise 的异步性质,我一直认为让 XMLHttpRequest 同步是好的,但由于我的浏览器警告我,我想确认一下。

mwe 将是:

call(arg) {
    return new Promise(resolve => {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8080?' + arg.name, false);
        xhr.send();
        resolve({body: {result: xhr.responseText}});
    });
}

最佳答案

Should I call XMLHttpRequest async within promise?

是的,异步的(不是同步的)。

Due to the async nature of the promise, I always assumed that having the XMLHttpRequest sync is fine...

它不是,有几个原因:

  1. 异步另一个线程 不同。您仍在阻塞主 UI 线程。

  2. 无论如何,promise 执行器函数(您传递给 new Promise 的函数)都是同步执行的。所以在 ajax 调用完成之前,您的 call 不会返回,因为它是一个同步调用。

promise 不会改变正在完成的工作的性质。它们只是提供一致的、标准化的语法来观察正在完成的工作的结果(通常是异步工作,但不一定非得如此)。

唯一使异步成为 thencatchfinally 处理程序的调用。有关详细信息,请参阅此代码段中的注释和结果:

// The promise executor is called *synchronously*.
// This outputs 1, 2, 3, not 1, 3, 2:
console.log(1);
new Promise(resolve => {
  console.log(2);
  resolve();
});
console.log(3);

// `then`, `catch`, and `inally` handlers are called asynchronously, even if
// the promise is already settled (because it would be chaotic to call them
// synchronously *sometimes* [because the promise is already settled when you
// call `then`/`catch/`finally`] but not *other* times [because it isn't
// settled yet when you call `then`/`catch/`finally`]).
// This outputs A, B, C, not A, C, B
console.log("A");
Promise.resolve().then(() => console.log("C"));
console.log("B");

不要使用同步 ajax,在 2019 年没有充分的理由这样做。


旁注:如果你想要启用 promise 的 ajax,请使用 fetch .

关于javascript - 我应该在 promise 中调用 XMLHttpRequest async 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116269/

相关文章:

javascript - 如何解决 wkhtmltopdf 中的 javascript 或 http 错误?

javascript - Threejs - 仅使用 THREE.Points 动态计算相机位置

javascript - 使用 lodash 进行嵌套数组分组

javascript - 如何在 typescript 中正确处理promisifyAll?

python - Scrapy爬虫不处理XHR请求

javascript - 如何替换字符串中所有但第一次出现的模式

vue.js - 在 Vue 3 中将数据对象设置为来自 Promise 的值

javascript - 是否有可能检测到 promise 链的结束

javascript - CORS "No ' Access-Control-Allow-Origin' header is present“但有

javascript - 如何从 xhr.responseText 获取 "Data"字段?