1. callback
var fn1=function(){console.log("func1")}
var fn2=function(fn){
setTimeout(function(){
console.log("func2")
fn() //不能写fn,这只是函数名,要写fn()才是触发
},500)
}
var fn3=function(){console.log("func3")}
//函数名作为参数传入fn2
fn1()
fn2(fn3) //将函数名传进去
2. promise
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
var fn1=function(){console.log("func1")}
var fn2=function(){
return new Promise((resolve,reject)=>{
setTimeout(function(){
console.log("func2")
resolve()
},500)
})
}
var fn3=function(){console.log("func3")}
//用then来管理先后次序
fn1()
fn2().then(()=>{fn3()})
3. async/await
用一个函数来安排次序,async/await出现在一个函数里
var fn1=function(){console.log("func1")}
var fn2= function(){
return new Promise((resolve,reject)=>{
setTimeout(function(){
console.log("func2")
resolve()
},500)
})
}
var fn3=function(){console.log("func3")}
async function execFunc(){
fn1()
await fn2()
fn3()
}
execFunc()
原文地址:https://www.cnblogs.com/KellyChen/p/9054017.html