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

Jus*_*gin 2 javascript httprequest axios

我想使用 Axios 库发送多个请求。所以,根据文档,我可以用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 
  }));
Run Code Online (Sandbox Code Playgroud)

但为什么我需要写

.then(axios.spread(function (acct, perms) {
    // Both requests are now complete 
  }));
Run Code Online (Sandbox Code Playgroud)

代替

.then(function (acct, perms) {
        // Both requests are now complete 
      });
Run Code Online (Sandbox Code Playgroud)

如果它也能正常工作吗?

par*_*lad 6

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

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);
}));
Run Code Online (Sandbox Code Playgroud)