Skip to content

Instantly share code, notes, and snippets.

@masui masui/promise.coffee
Last active Aug 29, 2015

Embed
What would you like to do?
Promiseの例
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
You can’t perform that action at this time.