gpt4 book ai didi

javascript - 为什么需要在 axios.all 回调中使用 spread 函数?

转载 作者:行者123 更新时间:2023-12-03 05:39:13 24 4
gpt4 key购买 nike

我想使用 Axios 库发送多个请求。所以,根据docs ,我可以用 all 方法来做到这一点。这是示例:

function getUserAccount() {
return axios.get('/user/12345');
}

function getUserPermissions() {
return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));

但是为什么我需要写

.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));

而不是

.then(function (acct, perms) {
// Both requests are now complete
});

它也能正常工作吗?

最佳答案

您需要使用axios.spread,因为它用于将参数数组分散为多个参数。这可以防止您使用 axios.all 发出多个 ajax 请求时出现错误。

axios.all([
axios.get('https://api.github.com/users/abc');
axios.get('https://api.github.com/users/abc/repos')
])
.then(axios.spread(function (userResponse, reposResponse) {
console.log('User', userResponse.data);
console.log('Repositories', reposResponse.data);
}));

关于javascript - 为什么需要在 axios.all 回调中使用 spread 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40612250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com