我在 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...
它不是,有几个原因:
异步 与另一个线程 不同。您仍在阻塞主 UI 线程。
无论如何,promise 执行器函数(您传递给 new Promise
的函数)都是同步执行的。所以在 ajax 调用完成之前,您的 call
不会返回,因为它是一个同步调用。
promise 不会改变正在完成的工作的性质。它们只是提供一致的、标准化的语法来观察正在完成的工作的结果(通常是异步工作,但不一定非得如此)。
唯一使异步成为 then
、catch
和 finally
处理程序的调用。有关详细信息,请参阅此代码段中的注释和结果:
// 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
.