async/await

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
// async function like a auto-execute generator function. Juse like co.
// co + generator yield similar with async/await

function f1(ret) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (ret) resolve(ret)
else reject('err');
}, 1000)
});
}

// async function return a promise;
async function f2() {
// you can use Promise.all to parallel execute function.
let rets = await Promise.all([f1('f1_1'), f1('f1_2')]);
// throw new Error('abc');
return rets;
}

// you can use catch function to catch async function error.
// also you can use try-catch to catch error in async function inner.
f2()
.then(console.log)
.catch(console.error);


// -----------------------
// similar code
co(function* () {
let rets = yield Promise.all([f1('f1_1'), f1('f1_2')]);
return rets;
})
.then(console.log)
.catch(console.error);
本站采用「署名 4.0 国际」进行许可。