使用promise解决异步编程:
语法:
function jax(type, url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(type, url, true);
xhr.send();
xhr.onload = function () {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response))
} else {
reject("请求失败")
}
}
xhr.onerror = function () {
reject("请求失败")
}
})
}
jax("get", "http://www.liulongbin.top:3005/api/getnewslist").then(
res => {
console.log("res", res);
}
).then(
() => {
return jax("get", "http://www.liulongbin.top:3005/api/getnewslist")
}
).then(
res => {
console.log("res", res);
}
).then(
() => {
return jax("get", "http://www.liulongbin.top:3005/api/getnewslist")
}
)