async/await of ES7 is one my fav
proposals, that would for sure change the way we handle asynchronous code in javascript!
Let see it's application with few examples:
Promise sample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| let p1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('Promises 1 '); }, 30);
});
}
let p2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('Promise 2'); }, 10);
});
}
async function getVal() {
var res1 = await p1();
var res2 = await p2();
return res1 + res2;
}
(async function() {
var res = await getVal();
console.log(res); // Promise 1 Promise 2
}());
|
FS stuff:
1
2
3
4
5
| var lieFS = require('lie-fs'); // Promisifed FS.
(async function() {
var list = await fs.readdir('~/');
console.log(list);
}());
|
Chain animation [From the spec]:
1
2
3
4
5
6
7
8
9
| async function chainAnimationsAsync(elem, animations) {
var ret = null;
try {
for (let anim in animations) {
ret = await anim(elem);
}
} catch(e) { /* ignore and keep going */ }
return ret;
}
|
async await fetch!
1
| let data = await (await fetch(url)).json()
|
Do let me know if you have your own set, until then happy async/await!