-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathbasic.js
60 lines (48 loc) · 1.41 KB
/
basic.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
49
50
51
52
53
54
55
56
57
58
59
60
var fs = require('fs');
var Promise = require('bluebird');
var async = require('..').async;
var await = require('..').await;
// A function that returns a promise.
function delay(milliseconds) {
return Promise.delay(milliseconds);
}
// A thunked version of fs.readFile.
function readFile(filename) {
return function (callback) {
return fs.readFile(filename, callback);
};
}
// A slow asynchronous function, written in async/await style.
var longCalculation = async (function (seconds, result) {
await (delay(seconds * 1000));
return result;
});
// Another synchronous-looking function written in async/await style.
var program = async (function () {
try {
console.log('zero...');
var msg = await(longCalculation(1, 'one...'));
console.log(msg);
msg = await(longCalculation(1, 'two...'));
console.log(msg);
msg = await(longCalculation(1, 'three...'));
console.log(msg);
var file = await(readFile('NonExistingFilename'));
msg = await(longCalculation(1, 'four...'));
console.log(msg);
} catch (ex) {
console.log('Caught an error');
}
return 'Finished!';
});
// Execute program() and print the result.
program().then(function (result) {
console.log(result);
});
// Outputs (with one second delays between the numbers):
// zero...
// one...
// two...
// three...
// Caught an error
// Finished!