function delay(fn) {
setTimeout(() => {
fn()
console.log('你好')
}, 0)
}
delay(() => {
console.log('kaishi')
})
複製代碼
這個回調寫在加載的delay函數內,若是是多重回調,那麼恭喜,你會在delay函數中寫上delay(()=>{}, ()=> {}, ()=>{})promise
<!--代碼-->
function delay(name) {
return new Promise((resolve, reject) => {
setTimeout(()=> {
resolve(name)
}, 2000)
})
}
delay('laoxie').then((res) => {
console.log(res)
})
<!--進入鏈式操做了-->
delay('laoxie').then((res) => {
console.log(res)
return delay('laoqin')
}).then((res) => {
console.log(res)
return delay('laomeng')
}).then((res) => {
console.log(res)
})
複製代碼
看上去簡潔很多,可是鏈式操做咋一看比回調看上去舒服多了,可是若是太長看上去仍是很彆扭,尤爲是是鏈式操做過長或者存在catch操做時koa
function delay(name) {
return new Promise((resolve, reject) => {
setTimeout(()=> {
resolve(name)
}, 2000)
})
}
async function getdata() {
var val1 = await delay('haifu');
console.log(val1)
var val4 = 1
console.log(val4)
var val2 = await delay('hao');
console.log(val2)
var val3 = await delay('fangl');
console.log(val3)
}
getdata()
複製代碼
async包裹的函數,函數做用域內部的內容簡直就是同步代碼,順著手往下寫的感受。異步