2016年11月29日 星期二

[async, new command] 最簡單的方式安裝使用 async/await

How to use async/await
GitHub: Download

Google doc: This document.
非同步處理是學習使用 node.js 的核心, 現在有新指令 async/await 即將發佈. 將大幅改善程式碼處理非同步的問題.  網路上有一堆範例程式, 但是怎麼執行呢? 要怎麼嘗鮮使用呢?  現在來示範一下, 我完全參考這篇的做法.

因為 V8 已經把 async/await 等新的處理非同步功能 build 進 night build 了. 只要拉 v8 nightbuild code, 然後就可以享受 async/await 的最新功能. 你不需要再像以前一樣, 弄一堆煩死人的 babel 相關的套件.

下面提供兩種方式, 讓你玩新指令.
  1. Docker Version: 只要三個指令, 完全攻略自動安裝完成. 讓你專注在 js code 上.
  2. 手動 Version: 一步一步安裝必要套件與設定, 讓你知道 Docker 版本的 script 是怎麼做的.

Enjoy & Good Luck.
Jing.

Docker Version

# pull the example
cd ./example/async_new_function

# Step 1:  設定使用 nightbuild 版本 node js
. ./01_docker_init.sh

# Step 2: 寫 code
vi example.js

# Step 3: Run
. ./docker_run.sh
E.g.


Manual Version

Step 1:  設定使用 nightbuild 版本 node js
#!/bin/bash

function install_nightbuild(){
 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash

 # load nvm
 export NVM_DIR="/root/.nvm"
 [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"


 NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly
 nvm install 7
 nvm use 7
}

install_nightbuild


E.g.


Step 2: 寫 code
'use strict';

// app.js
const timeout = function (delay) {  
 return new Promise((resolve, reject) => {
   setTimeout(() => {
     resolve()
   }, delay)
 })
}

async function timer () {  
 console.log('timer started')
 await Promise.resolve(timeout(100));
 console.log('timer finished')
}

timer()


Step 3: Run
node --harmony-async-await example.js

Verification

Reference