前端异步请求解决方案
前言
JavaScript是一门单线程的语言,同一时间节点只能做一个任务,默认是从前往后一次执行。
同步任务:
指在主线程上排队执行的任务,只有前一个任务执行完毕,才能继续执行下一个任务。
异步任务:
指不进入主线程,而是进入任务队列的任务。只有任务队列通知主线程,某个异步任务可以执行了。后一个任务不等前一个任务结束就执行。
异步操作:
(1)定时器函数
(2)事件函数
(3)网络请求
(4)promise对象(then\catch)
(5)generator函数
(6)await/aysic
下面是几种异步请求的解决方案
一、回调函数
函数A作为参数传递到函数B中,并且函数B执行函数A。函数A就是回调函数,将回调函数作为参数。
二、promise对象
promise对象的作用:
处理异步操作
解决回调地狱
let pro = new Promise(function(resolve,reject){
if(1){ //成功操作
resolve("成功了");
}else{ //失败操作
reject("失败了");
}
})
Promise的参数是一个函数,该函数有两个参数resolve和reject。
操作成功执行resolve(),操作失败执行reject()。
Promise对象的三种状态:
开始状态:pendding,初始化状态
成功状态:fulfilled,调用resolve(),实例的状态变为fulfilled
失败状态:rejected,调用reject(),实例的状态变为rejected
状态转化:
操作成功:pendding -->fulfilled
操作失败:pendding -->rejected
状态转化是的单项的,不可逆。
then()、catch()
then():promise实例化对象.then(function(res){}) 成功执行then方法,第一个then方法的参数 res是resolve函数的参数,剩下的then方法的参数res是上一个then方法的返回值,可以解决回调地狱
catch():promise实例化对象.catch(function(err){}) 失败执行catch方法,err是reject函数的参数
pro
.then((res) => {
console.log(res); //成功了 resolve的参数
return "我是第一个then";
})
.then((res) => {
console.log(res); //我是第一个then
return "我是第二个then";
})
.then((res) => {
console.log(res); //我是第二个then
return "我是第三个then";
})
.then((res) => {
console.log(res); //我是第三个then
})
.catch((err) => {
console.log(err); //失败了 reject的参数
});
三、async await
async:用于声明一个function是异步的,返回一个promise对象
await:必须在async声明的函数内部使用。
async function f(){
return 'async函数';
}
console.log(f()); //Promise
<script>
console.log(10);
async function async(){
console.log(20);
await console.log(40); //等待该语句以及与之同步的执行完再往下执行下一个语句
console.log(50);
}
async3();
console.log(30); //10 20 40 30 50
</script>
关键词await可以让JavaScript进行等待,直到一个promise执行并返回它的结果,JavaScript才会继续往下执行。
函数执行到await行会暂停不再往下执行。