JavaScript简单的Async/Await示例

时间:2022-06-01 17:42:24

Node 7.6 新增了async/await! 下面以一个简单可运行的示例来说明async /await的使用。

const axios = require('axios'); //基于promise的http请求框架
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve('☕'), 2000); // 延时两秒返回咖啡
});
}
async function go() {
try {
// 首先拿咖啡
const coffee = await getCoffee();
console.log(coffee); // ☕
//接着通过ajax的方式获取些数据
const wes = await axios('https://api.github.com/users/wesbos');
console.log(wes.data); // mediocre code
// 多个请求并发
//触发三个请求,获取它的promise
const wordPromise = axios('http://www.setgetgo.com/randomword/get.php');
const userPromise = axios('https://randomuser.me/api/');
const namePromise = axios('https://uinames.com/api/');
// 等待三个promise返回,然后把结果赋值给三个变量
const [word, user, name] = await Promise.all([wordPromise, userPromise, namePromise]);
console.log(word.data, user.data, name.data); // cool, {...}, {....}
} catch (e) {
console.error(e); // ????
}
}
go();