js获取异步请求的return值
时间: 2024-10-12 22:05:27 浏览: 12
在JavaScript中,获取异步请求(如fetch、axios或XMLHttpRequest等)的返回值通常涉及到处理回调函数、Promise、async/await或者是async函数。这里以Promise为例来说明:
1. **回调函数**:
```javascript
function asyncFunction() {
return fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => data.result); // 这里data就是异步请求的返回值
}
```
2. **Promise链式调用**:
```javascript
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.result;
}
const result = getData(); // 等待请求完成并获取结果
```
3. **async/await**:
```javascript
async function getAsyncData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.result;
} catch (error) {
console.error(error);
}
}
const returnedValue = getAsyncData();
```
阅读全文