Last active
February 15, 2016 16:07
-
-
Save bokuo-okubo/bb8914d9417028422feb 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
'use strict'; | |
const HTTP = require('http'); | |
/* | |
@param url: String ゆーあーるえる | |
@param conv: String -> String 型の関数 | |
*/ | |
function getURL(url, conv) { | |
/* | |
resolve, rejectはそれぞれ 処理成功時、失敗時に(利用ユーザが)呼びだす関数 | |
*/ | |
return new Promise( (resolve, reject) => { | |
HTTP.get(url, (res) => { | |
let body = ''; | |
res.on('data', (chunk) => { body += chunk }); | |
res.on('end', () => { resolve(conv(body)) }); | |
res.on('error', (err) => { reject(err) }); | |
}); | |
}); | |
} | |
/* | |
stub | |
genEncodeConverter: エンコーダ(文字列を受け取って、指定されたエンコードで変換して返す)を返す | |
@param encoding: String | |
@param decoding: String | |
*/ | |
function genEncodeConverter(encoding, decoding) { | |
//let iconv = new Iconv(encoding, decoding); | |
return (str) => { | |
// some encoding process | |
return str; | |
} | |
} | |
// main | |
let UTF8 = 'UTF-8//TRANSLIT//IGNORE'; | |
let conv = genEncodeConverter('sjis', UTF8) | |
let pro = getURL('http://example.com', conv); | |
pro.then( (body) => { console.log(body) }); | |
console.log(pro); | |
console.log('=============================='); | |
/* | |
ここでproはPromiseオブジェクト。constructor (new Pomise時)と同じように、 | |
第一引数は onFullfilled(resolve), 第二引数は(無視可能)、onRejected(error) | |
それぞれ関数の型は、 | |
onFullfilled: (直前処理のresolveで投げられるインスタンスの型) -> (往々にして同じ型、連鎖しづらいから cf.静的型付けの場合) | |
onRejected: ((往々にして) Errorオブジェクト) -> (往々にしてErrorオブジェクト) | |
また、reject時のハンドリングは例外のキャッチと同じノリでこのようにもかける | |
``` | |
pro | |
.then( (body) => { /* 成功じのbodyしょり*/ }) | |
.catch( (error) => { console.log('エラーだ: ' + e) } ); | |
``` | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment