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
function takeLongTime() {
return new Promise(resolve = >{
setTimeout(() = >resolve("long_time_value"), 1000);
});
}

function getStockPrice() {
return new Promise((resolve, reject) = >{
if (new Date().getMinutes() > 14) {
resolve('success');
} else {
reject("http error...");
}
});
}

async function test() {
const v = await takeLongTime();
console.log(v);
try {
var stockPrice = await getStockPrice(v);
return stockPrice;
} catch(error) {
//这里会打印reject内容
console.log(error);
}
}

test();
//await关键字只能用在aync定义的函数内。async函数会隐式地返回一个promise,该promise的reosolve值就是函数return的值。
0%