【问题标题】:When exactly is Axios Promise resolvedAxios Promise 究竟何时解决
【发布时间】:2019-10-24 14:08:25
【问题描述】:

我想我知道这个问题的答案,但我没有找到任何关于它的文档,所以我想确保我没有错过任何东西。

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() 很重要? p>

我知道我总是可以这样做:

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);
});

但这只会在所有承诺都解决后触发,如果...-codeblocks 中有一些 compute-heavy 的东西,我不只是想开始在响应所有 API 请求后在它们上执行。

【问题讨论】:

  • 你问题的最后一部分让我猜想你正在尝试解决某种你没有问到的问题。这看起来像 XY 问题。你想解决什么问题?
  • 实际上,我的运行代码完全没有问题,只是我处于知识的边缘(对 javascript 和 ReactJS 相当陌生),虽然我看到了潜在的竞争条件,我不确定它是否真的存在,如果存在,解决它的最佳做法是什么。此外,我希望代码具有良好的风格,以便其他人可以轻松使用它。
  • 您问题中的最后一个代码 sn-p 不需要 thenPromise.all 内,因为来自承诺的数据已经可用,通过解构 Promise.all 的 @ 来使用它们987654337@ 的参数类似于[res1, res2]
  • Promise.all([prom1, prom2]).then(([res1, res2]) => {

标签: javascript reactjs asynchronous axios es6-promise


【解决方案1】:

但是prom1真的只有在axios的.then()执行后才解决吗?

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

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

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

【讨论】:

  • 这个答案中唯一缺少的是 .then 返回一个新的 Promise,它不再是来自 axios.get 的原始 Axios Promise。
  • 感谢您的快速回复! @Quentin你说得对,我在考虑一个具体案例:如果最后一个承诺得到解决,我会在Promise.all().then(...)上方调用promN.then(...),这些将同步执行,上面的.then()将首先执行还是两者都并行执行? @EmileBergeron 我不知道,谢谢你的信息!
  • @AskingAround 它们是异步的,这意味着如果prom1 的解析时间比prom2 长(网络延迟等),prom2then 将首先被调用。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2019-08-10
  • 1970-01-01
  • 2019-10-12
  • 2018-03-03
  • 2020-08-01
相关资源
最近更新 更多