Last active
December 14, 2019 15:08
-
-
Save jation/a55c2254d93cf1dd2f1258f6508dddf0 to your computer and use it in GitHub Desktop.
Promise async await tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Promise, async, await 快速教程 | |
// 包含异步执行顺序控制、异常控制、多异步排序控制 | |
// t1 多异步串行、异常处理 | |
function t1(){ | |
function stepA(){ | |
return new Promise((resolve, reject) => { | |
setTimeout(()=>{ | |
Math.random() > 0.5 ? resolve('A') : reject('~A~') | |
}, 300) | |
}) | |
} | |
function stepB(pre){ | |
return new Promise((resolve, reject) => { | |
setTimeout(()=>{ | |
resolve(pre + 'B') | |
}, 100) | |
}) | |
} | |
async function runAB(){ | |
let A | |
try{ | |
A = await stepA() | |
} catch (e) { | |
A = e | |
} | |
const B = await stepB(A) | |
console.log(B) | |
} | |
function stepC(){ | |
return new Promise((resolve, reject) => { | |
runAB().then(()=>{resolve('done C')}) | |
}) | |
} | |
async function runC(){ | |
let c = await stepC() | |
console.log(c); | |
} | |
runC() | |
} | |
// t1() | |
// 多异步并行、异常 | |
function t2(){ | |
function s1(){ | |
return new Promise((r, rj)=>{ | |
setTimeout(()=>{ | |
Math.random() > 0.5 ? r('s1') : rj('s1') | |
console.log('s1') | |
}, 50) | |
}) | |
} | |
function s2(){ | |
return new Promise((r, rj)=>{ | |
setTimeout(()=>{ | |
r('s2') | |
console.log('s2') | |
}, 100) | |
}) | |
} | |
function run(){ | |
Promise.all([s1(), s2()]).then(()=>{ | |
console.log('done') | |
}).catch(err=>{ | |
console.error(err.toString()) | |
}) | |
} | |
run() | |
} | |
t2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment