看了一些网上的推荐,但是同步依然借助的async、await,这不是我需要的。这里记录下不依赖async来实现同步请求。
function syncRequest(url, param){
const xhr = new XMLHttpRequest();
xhr.open("GET", url, false); // false 表示同步请求
xhr.send(param);
if (xhr.status === 200) {
let result = JSON.parse(xhr.responseText);
return result;
} else {
throw new Error("请求失败: " + xhr.status);
}
}
调用
function A(){
console.log('a');
let b = syncRequest('xx://xxxx?=xx', null);
console.log(b);
console.log('c')
}