Last active
August 29, 2015 14:27
-
-
Save masui/fc7d44026d298c0940d1 to your computer and use it in GitHub Desktop.
Promiseの例
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
fs = require 'fs' | |
readFile = (filename, enc) -> | |
new Promise (fulfill, reject) -> | |
fs.readFile filename, enc, (err, res) -> # readFile()は非同期関数 | |
if err | |
reject err | |
else | |
fulfill res | |
convJSON = (data) -> | |
new Promise (fulfill, reject) -> | |
try | |
fulfill JSON.parse(data) # JSON.parse()は同期関数 | |
catch ex | |
reject ex | |
# | |
# Promiseを返すものをチェインしていけるのだと思う | |
# コールバックを書かなくて良いので綺麗に書ける | |
# | |
readFile 'test.json', 'utf8' | |
.then convJSON | |
.catch console.log # readFileのエラー | |
.then console.log | |
.catch console.log # convJSONのエラー |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment