LoginSignup
7
10

More than 5 years have passed since last update.

fibers on node.js事始め

Posted at

fiberを使うと、コールバック地獄からいくらか解放されるかもしれない。

npm install fibers

とした上で、下記のコードを実行してみる

// url_fetch_test.js
var Fiber = require("fibers")
  , http  = require('http');

var main = function() {
  console.log("process start");

  var fiber = Fiber.current;

  http.get("http://www.google.com/index.html", function(res) {
    fiber.run(res);
  });

  var res = Fiber.yield();
  console.log("Got response: " + res.statusCode);
};

Fiber(main).run();

console.log("out of Fiber");
% node url_fetch_test.js
process start
out of Fiber
Got response: 302

http.getをしたタイミングで、nodeのメインスレッドはmain関数から外れてしまい、最後の行のconsole.log("out of Fiber");の行を実行する。
main関数の残りの処理は、Filber.yield()関数から値が返ってきてから再開される。
コールバックそのものは減らせないとしても、書き方次第で可読性を増すことはできるかもしれない。

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10