Async, Await / Promise
var request = require('request');
/* version 1: Normal,
function google(next = () => { }) {
request('https://www.google.com').on('response', function (err, body) {
console.warn('google arrive');
next();
})
}
function yahoo(next = () => { }) {
request.get('https://www.yahoo.com').on('response', function (err, body) {
console.warn('yahoo arrive');
next();
})
}
/*
Version 2: Promise,
function google(next=()=>{}) {
return new Promise(function(resolve, reject){
request('https://www.google.com').on('response', function (err, body) {
console.warn('google arrive');
next();
resolve();
})
});
}
function yahoo(next=()=>{}) {
return new Promise(function(resolve, reject){
request.get('https://www.yahoo.com').on('response', function (err, body) {
console.warn('yahoo arrive');
next();
resolve();
})
});
}*/
/*google(()=>{
yahoo(()=>{
google();
})
})*/
/*google()
.then(()=>{
return yahoo();
}).then(()=>{
return google();
})*/
function google(next = () => { }) {
return new Promise(function (resolve, reject) {
request('https://www.google.com').on('response', function (err, body) {
console.warn('google arrive');
next();
resolve();
})
});
}
function yahoo(next = () => { }) {
return new Promise(function (resolve, reject) {
request.get('https://www.yahoo.com').on('response', function (err, body) {
console.warn('yahoo arrive');
next();
resolve();
})
});
}
async function seq(){
await google();
await yahoo();
await google();
}
seq();
由於尚未支援到async/await ES7 的 feature 所以必須設定flag 打開此feature
node --harmony-async-await index.js
Last updated
Was this helpful?