javascript - Axios Promise 到底什么时候解决

标签 javascript reactjs asynchronous axios es6-promise

我想我知道问题的答案,但我没有找到任何相关文档,所以我想确保我没有遗漏任何东西。

const prom1 = axios.get('/user/1').then(res => {
  /* do stuff with response */
  return res;
});
const prom2 = axios.get('/user/2').then(res => {
  /* do stuff with response */
  return res;
});
Promise.all([prom1, prom2]).then(() => setLoading(false));

在上面的示例中,Promise.all().then 似乎总是axios.get 之后执行().then()。但是prom1真的只是执行完axios的.then()之后才解析的吗?

我的理解/猜测:

axios.get('/user/1').then(...);
/* THOSE TWO ARE THE SAME */
const prom = axios.get('/user/1');
prom.then(...);

Promise.all() 中的 .then() 总是在 之后 axios.get( ).then() 是它们是同步执行的,因此首先调用哪个 .then() 很重要?

我知道我可以随时做:

const prom1 = axios.get('/user/1').then(res => res);
const prom2 = axios.get('/user/2').then(res => res);
Promise.all([prom1, prom2]).then(() => {
  prom1.then(...);
  prom2.then(...);
  setLoading(false);
});

但这只会在所有 promise 都已解决并且如果 ... 代码块中有一些计算量大的东西发生时才会触发,我不想在响应所有 API 请求后才开始执行它们。

最佳答案

But is prom1 really only resolved after the .then() of axios has been executed?

prom1 是调用 then() 方法的返回值,所以是。

The reason the .then() from Promise.all() will always be executed after the axios.get().then() is that they are executed synchronous and therefore it matters which .then() is being called first?

没有。它们是异步执行的。 Promise.all() 返回的 promise 不会解决,除非并且直到它传递的数组中的所有 promise 都得到解决。这些 promise 解决的顺序无关紧要。

关于javascript - Axios Promise 到底什么时候解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543200/

相关文章:

php - 在 php 中进行 AES 加密,然后使用 Javascript (cryptojs) 解密

javascript - 多个选择器不适用于 jQuery 和 find() 方法

css - ReactJS 在页面调整大小时更改图像/ Logo

reactjs - React-router-reduxsyncHistoryWithStore 与 React-router 崩溃/传递状态

reactjs - 在 React 应用程序中创建一个 "base URL"常量

node.js - Q.all 在 forEach 之前运行

javascript - JS : async function implicitly unwraps promise?

Javascript从字符串中删除div文本

javascript - 如何在 Blogger 中隐藏 javascript 代码以防止检查页面元素?

node.js - 同步 Mongoose 请求