1、回调函数
setTimeout(()=>{},1000)
解决了同步的问题(同步时,所有的任务按顺序执行,会拖延整个程序的执行)
缺点:当所有的异步操作结果之间存在依赖关系时,会形成回调函数的嵌套。
嵌套会导致函数之间耦合性太高,错误无法正确抛出。
2、promise
promise解决异步操作,将异步操作放在promise容器中。通过链式调用,每次then后返回一个新的promise。
return new Promise(function(resolve,reject){
if(resolve){resolve(value)}
else{reject(error)}
})
3、async/await
代码清晰,通过同步代码取代then的链式调用
async handler(){
await change("/a/1");
await change("/a/2");
await change("/a/3");
}
change(value){
return new Promise((resolve,reject)=>{
if(resolve){resolve(value)}
else{reject(error)}
})
}
多个异步之间没有依赖关系,promise.all()
多个异步之间存在依赖关系,可以通过async/await。
执行顺序
遇到await时,先执行await后的函数,然后跳出async函数,执行后面的js栈中的代码,执行完之后会再次跳入async函数中。
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
console.log('script end');
script start
async1 start
async2
promise1
script end
async end
promise2
setTimeout