javascript - 如何获得基于异步等待/承诺的响应
问题描述
所以我有一个代码如下。有一个函数调用 2 个 axios 请求来获取一些示例 API 数据。
function fetch_records(){
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
axios.get(api_url1)
.then(function (response) {
console.log('Data1 received: ',response);
})
.catch(function (error) {
console.log(error);
})
axios.get(api_url2)
.then(function (response) {
console.log('Data2 received: ',response);
})
.catch(function (error) {
console.log(error);
})
}
然后我想运行这个函数 fetch_records() 如下
console.log('Script started');
fetch_records();
console.log('Script ended');
所以输出应该是
Script started
... api response data ...
Script ended
但是因为 Javascript 是异步的,所以它总是给出如下输出
Script started
Script ended
... api response data ...
我相信 async/await 或 promise 用于实现我想要的响应,但我不确定如何准确使用它。
解决方案
只需使用async/await
关键字,但请记住 JS 始终是 JS。
async function fetch_records() { // a async function
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
// waterfall way
const data1 = await axios.get(api_url1); // await
console.log('Data1 received: ', data1);
const data2 = await axios.get(api_url2); // await
console.log('Data2 received: ', data2);
// parallel way
// const [data1, data2] = await Promise.all([
// axios.get(api_url1),
// axios.get(api_url2)
// ]);
// console.log(data1, data2);
}
(async () => {
try {
console.log('Script started');
await fetch_records(); // await a async function (Thenable object)
console.log('Script ended');
} catch(err) {
console.error(err);
}
})();
推荐阅读
- tensorflow - 连接局部变量时出错
- javascript - 以下比较和对象属性实现有什么问题,它只返回 2 个值(JS)?
- python - 关闭脚本未在 Google Cloud VM 上执行
- android - 无法将我的 android 应用程序连接到网络,只能通过我的家庭 wifi 才能正常工作
- database - ARM 模板部署 - CosmosDB 配置失败 - 请求率很大。可能需要更多请求单位,因此未进行任何更改
- reactjs - 在浏览器中单击后退按钮时加载上一页
- c# - 使用 Microsoft Playwright 在 Azure Function Linux 消费计划中创建本地 PDF 文件
- c# - 使用 C# 在 BigQuery 中组合非平面架构
- search - Parallelizing search in a 2D array on CUDA
- bash - 在 bash 变量中使用 find 计算找到的路径数