js如何将每次接口返回数据存起来
时间: 2024-10-13 08:15:01 浏览: 21
在JavaScript中,如果你想将每次从接口获取的数据存储起来,你可以使用数组、对象或者更复杂的数据结构,比如Map或Set,取决于数据的具体情况和你需要的操作。这里有几个基本的方法:
1. **数组**:如果你每次请求的数据可以按顺序添加,可以用数组存储:
```javascript
let dataStore = [];
fetch('http://example.com/api')
.then(response => response.json())
.then(data => {
dataStore.push(data);
// 对接收到的data进行其他操作...
});
```
2. **对象**:如果每个数据项有唯一的键,可以使用对象存储,键通常对应API返回的数据标识:
```javascript
let userData = {};
fetch('http://example.com/api/user')
.then(response => response.json())
.then(user => {
userData[user.id] = user;
// 存储用户数据...
});
```
3. **Promise.all() 或者 async/await**:如果需要同时处理多次请求并保存结果,可以使用`Promise.all()`或async/await:
```javascript
async function fetchData() {
const [userData, apiData] = await Promise.all([
fetch('http://example.com/api/user'),
fetch('http://example.com/api/data'),
]);
const userDataJson = await userData.json();
const apiJson = await apiData.json();
// 将数据合并到一个对象中...
}
fetchData().then(() => {
// 数据已存入变量中...
});
```
阅读全文
相关推荐


















