-
Notifications
You must be signed in to change notification settings - Fork 25
/
16-async-await.js
51 lines (42 loc) · 1.08 KB
/
16-async-await.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
var numbers = [3, 1, 7];
var constant = 2;
// use an promise-returning multiply
var Promise = require('bluebird');
function mul(a, b) {
return Promise.resolve(a * b);
}
// use a promise-returning print
function print(n) {
console.log(n);
return Promise.resolve();
}
var byConstant = mul.bind(null, constant);
// multiplies each number one at a time
function mulAll(numbers) {
return Promise.map(numbers, byConstant, { concurrency: 1 });
}
// prints each number one at a time
function printAll(numbers) {
return Promise.map(numbers, print, { concurrency: 1 });
}
// uses https://github.com/yortus/asyncawait
// to execute promise-returning calls just like sync code
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var multiplyAndPrint = async (function () {
var multiplied = await (mulAll(numbers));
console.log('multiplied all numbers');
await (printAll(multiplied));
console.log('printed all numbers');
});
multiplyAndPrint().then(function () {
console.log('all done');
});
/*
multiplied all numbers
6
2
14
printed all numbers
all done
*/