forked from ryeo/nodejs-using-futures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
48 lines (37 loc) · 1.22 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/************************ require ********************************************/
require('./utils.js');
var Fiber = require('fibers');
var Future = require('fibers/future');
/*****************************************************************************/
/************************ main ***********************************************/
function doAsyncWork (callback) {
setTimeout(function () {
callback && callback(null /* no error */, 'hello world');
}, 3000);
}
// Doing async work with Fibers
function doAsyncWorkWithFiber () {
var fiber = Fiber.current;
setTimeout(function () {
fiber.run('result of work');
}, 3000);
var results = Fiber.yield();
return results;
}
var wrapAsyncWorkWithFuture = Future.wrap(doAsyncWork);
function doAsyncWorkWithFuture () {
var future = new Future;
setTimeout(function () {
future.return('result of work');
}, 3000);
return future.wait();
}
var handleRequest = function (i) {
print(i, 'handling request');
var results = wrapAsyncWorkWithFuture().wait();
print(i, 'after doAsyncWorkCall with result ' + results);
}.future();
handleRequest(1);
handleRequest(2);
handleRequest(3);
/*****************************************************************************/