UNPKG

1.73 kBJavaScriptView Raw
1var fs = require('fs');
2var Promise = require('bluebird');
3var async = require('..').async;
4var await = require('..').await;
5
6
7// A thunked version of fs.readFile.
8function stat(filename) {
9 return function (callback) {
10 return fs.stat(filename, callback);
11 };
12}
13
14// A slow asynchronous function, written in async/await style.
15var longCalculation = async (function (seconds, result) {
16 console.log('Starting ' + result);
17 await (Promise.delay(seconds * 1000));
18 return result;
19});
20
21// An async/await style function with both sequential and parallel operations.
22var compoundOperation = async (function () {
23 console.log('A: zero');
24
25 var result1 = await([
26
27 // Everything is this array will be computed in parallel.
28 longCalculation(1, 'A: one'),
29 1.5,
30 longCalculation(1, 'A: two'),
31 stat(__filename),
32 {
33 three: longCalculation(1, 'A: three'),
34 four: longCalculation(1, 'A: four'),
35 five: 'five'
36 }
37 ]);
38 console.log(result1);
39
40 // result2 won't start being computed until result1 above is complete.
41 var result2 = await ({
42
43 // Everything is this object will be computed in parallel.
44 k1: longCalculation(1, 'B: one'),
45 k2: longCalculation(1, 'B: two'),
46 k3: [
47 longCalculation(1, 'B: three'),
48 longCalculation(1, 'B: four'),
49 5,
50 'six'
51 ]
52 });
53 console.log(result2);
54
55 // Execution will reach here after result2 is complete.
56 return 'Finished!';
57});
58
59// Start the compound operation.
60compoundOperation().then(function (result) { console.log(result); });