# JavaScript 同步(sync) / 非同步(async) async/await base on promise ## 範例 - 異步 ```javascript function fn1(){ setTimeout(funtion(){ console.log(1) },0) } function fn2(){ console.log(2) } fn1() fn2() //結果:2、1 ``` ## Promise 類似 Callback 概念 ```javascript function fn1(){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(1) resolve() },0) }) } function fn2(){ console.log(2) } fn1().then(fn2) // fn1 做完,做 fn2 //結果:1、2 ``` ## async await 同步的視覺,非同步的享受 ```javascript function fn1(){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(1) resolve() },0) }) } function fn2(){ console.log(2) } function fn3(){ setTimeout(function(){ console.log(3) },0) } async function test(){ await fn1() fn2() } test() //結果:1、2 ``` ## generator
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up