Created
November 14, 2016 07:01
-
-
Save oscar60310/24b54f30286453eeed40e9e84fb58486 to your computer and use it in GitHub Desktop.
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
var request = require('request'); | |
var url1 = 'http://beta.json-generator.com/api/json/get/414r5rM-z'; | |
var url2 = 'http://beta.json-generator.com/api/json/get/VJqDcHMbM'; | |
/* normal callback */ | |
function getdata1(callback) | |
{ | |
request.get(url1,function (error, response, body) { | |
callback((JSON.parse(body)).success); | |
}); | |
} | |
function getdata2(s) | |
{ | |
request.get(url2,function (error, response, body) { | |
console.log(s + " " + (JSON.parse(body)).success); | |
}); | |
} | |
getdata1(getdata2); | |
/* Promise */ | |
function p_get1() | |
{ | |
return new Promise(function(resolve, reject){ | |
request.get(url1,function (error, response, body) { | |
resolve((JSON.parse(body)).success); | |
}); | |
}); | |
} | |
function p_get2(s) | |
{ | |
return new Promise(function(resolve, reject){ | |
request.get(url2,function (error, response, body) { | |
console.log(s + " " + (JSON.parse(body)).success); | |
}); | |
}); | |
} | |
p_get1().then(p_get2); | |
/* arrow */ | |
p_get1().then(s => p_get2(s)); | |
/* Generator */ | |
function* run(){ | |
var s1 = yield p_get1(); | |
yield p_get2(s1); | |
} | |
var gen = run(); | |
gen.next().value.then(function(r1){ | |
//第一個Promise結束後,把r1丟回給generator | |
gen.next(r1); | |
console.log('done'); | |
}); | |
/* async */ | |
// | |
/* arrow function */ | |
function add(a,b){ | |
return a+b; | |
} | |
console.log(add(1,2)); | |
var c = (a,b) => a+b; | |
console.log(c(1,2)); | |
var d = (a,b) => {if(a>b){return a;}else{return b;}}; | |
console.log(d(1,2)); | |
console.log(d(3,2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment