Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Last active March 7, 2016 20:54
Show Gist options
  • Save jooyunghan/36be94d2ad4b939bd510 to your computer and use it in GitHub Desktop.
Save jooyunghan/36be94d2ad4b939bd510 to your computer and use it in GitHub Desktop.
Promise 로 래핑하면서 오히려 실수할만한 내용.
process.on('message', function(message) {
console.log("message received", message);
process.send(message.toUpperCase(), function(err) {
console.log("replied",err);
});
});

Promise는 Haskell의 모나드와 달라서 이미 'fire'된 상태.

JooyungsMacBook:js jooyung.han$ node parent.js
sent
sent
message received abc
message received cde
received
replied null
received
replied null
[ 'ABC', 'ABC' ]
done
^C
JooyungsMacBook:js jooyung.han$ 

이를 해결하려면 interpreter패턴 혹은 Free monad를 사용해야.

var cp = require('child_process');
var child = cp.fork('child.js');
function write(message) {
return new Promise((resolve, reject) => {
child.send(message, err => {
console.log("sent")
if (err) {
reject(err); return;
} else {
child.once('message', message => {
console.log("received");
resolve(message);
});
}
});
});
}
Promise.all([write("abc"), write("cde")])
.then(result => console.log(result))
.then(()=> console.log("done"));
var cp = require('child_process');
var async = require('async');
var child = cp.fork('child.js');
function write(message, cb) {
child.send(message, err => {
console.log("sent");
if (err) {
cb(err);
} else {
child.once('message', message => {
console.log("received");
cb(null, message);
});
}
});
}
async.mapSeries(["abc", "cde"], write, (err, result) => {
console.log(result);
console.log("done");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment