iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 16
0
自我挑戰組

30 天 node.js 學習筆記系列 第 16

Day 16 await && async

1.在使用非同步(ajax / setTimeOut)動作時,會等在 called stack 中程式依序跑完,再去跑非同步事件的queue。

為了在非同步事件做完後再去做其他事必須去寫callback,但可能會造成波動拳,callback弄太深的窘境。

2.所以推出了async 的function,是讓有 async 前綴字的funciton ,中會等待有 await 前綴字的function,的非同步行為像是卡住一樣等他做完之後在往下做事,做起來會像是同步行為,( 但他只會等待Promise 物件包住的行為,直接寫ajax or setTimeOut不會有作用 )。

有個範例可以比較使用 Promise 與不使用 Promise 寫法差別

    // Promise
    var p = new Promise((resolve) => {
    	console.log('1');
    	setTimeout(resolve, 300);
    })
    
    p.then(() => new Promise((resolve) => {
    	console.log('2');
    	setTimeout(resolve, 300);
    }))
    .then(() => {
    	console.log('3')
    })
    // await && async
    var runTimeOut = async function () {
    	await new Promise((resolve) => {
          console.log('1');
          setTimeout(resolve, 300);
      })
    
      await new Promise((resolve) => {
          console.log('2');
          setTimeout(resolve, 300);
      })
    
       console.log('3')
    	
    }

上一篇
Day 15 call by value, call by share
下一篇
Day 17 this 的變化
系列文
30 天 node.js 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言