在这里插入代码片
## 1、axios同步请求
// 假设这是我们要请求的数据
function getSomething(n) {
return new Promise(resolve => {
// 模拟1s后返回数据
setTimeout(() => resolve(222), 1000);
});
}
function requestSomething() {
console.log(111);
getSomething().then(res => console.log(res));
console.log(333);
}
requestSomething() //这个时候会输出 111,333,222
// 如果想要等数据返回后再执行后面的代码,那么就要使用 async/await
async function requestSomething() {
console.log(111);
// 这时something会等到异步请求的结果回来后才进行赋值,同时不会执行之后的代码
const something = await getSomething();
console.log(something)
console.log(333);
}
requestSomething() //这个时候会输出 111,222,333
2、ajax同步请求
请求1和请求2中都用上async: false,
<body>
<div class="test"></div>
</body>
<script>
var a = "111"
$.ajax({
type: "GET",
url: 'http://sjsqbw.cn/upload/weixinhaobj15',
async: false,
dataType: "json",
success: function (res) {
console.log(res[0]._id)
a = res[0]._id
// setTimeout("alert('对不起, 要你久候')", 3000 )
}
})
$.ajax({
type: "GET",
url: 'http://sjsqbw.cn/upload/weixinhaobj15',
dataType: "json",
async: false,
success: function (res) {
console.log(res[0]._id)
console.log("a的值是"+a)
$(".test").text(a)
}
})
</script>