Skip to content

Instantly share code, notes, and snippets.

@masui
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masui/fc7d44026d298c0940d1 to your computer and use it in GitHub Desktop.
Save masui/fc7d44026d298c0940d1 to your computer and use it in GitHub Desktop.
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