const axios = require('axios');
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve('☕'), 2000); // 延时2秒
});
}
async function go() {
try {
const coffee = await getCoffee();
console.log(coffee); // ☕
// 异步请求
const wes = await axios('https://api.github.com/users/wesbos');
console.log(wes.data);
//
//并发三个请求
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();