You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Promise.all未按预期工作:未等待Promise完成即执行then代码

问题根源:removeFile函数的返回值未正确传递Promise

看起来你遇到的问题核心在于:Promise.all并没有等到你期望的异步操作完成就执行了后续的.then()块,导致输出顺序颠倒。

让我拆解一下背后的原因:

  • Promise.all会对传入的每一项进行处理:如果项不是Promise实例,它会自动把该值包装成一个立即resolve的Promise(比如undefined就会变成Promise.resolve(undefined))。
  • 如果你的removeFile函数没有正确返回由sleep(1500)生成的Promise链,而是默认返回了undefined,那么Promise.all会认为所有Promise都已完成,直接进入.then()块打印I execute after;而sleep(1500)的回调还是会在1500ms后执行,打印I execute——这正好和你看到的输出顺序一致。

你提到已经尝试给removeFile添加return,但大概率是return的位置写错了。比如如果把return写在.then()的回调内部,那函数本身还是不会返回Promise:

// 错误示例:return仅属于then回调,removeFile函数返回undefined
removeFile = (UUID) => { 
  const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)); 
  sleep(1500).then(() => { 
    console.log('I execute'); 
    return; // 这里的return不影响removeFile的返回值
  }); 
};

正确写法

你需要确保removeFile函数直接返回整个Promise链:

removeFile = (UUID) => { 
  const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)); 
  // 直接返回sleep生成的Promise(包括后续的then回调)
  return sleep(1500).then(() => { 
    console.log('I execute'); 
  }); 
};

这样,this.props.onRemove(fileId)会返回一个需要等待1500ms才会resolve的Promise,Promise.all会严格等待这个Promise完成后再执行.then()块,输出顺序就会符合预期:

I execute
I execute after

额外优化建议

其实你的场景里只需要等待单个Promise,完全可以去掉Promise.all简化代码:

onRemove = (fileId) => { 
  this.setState({ removing: true }); 
  this.props.onRemove(fileId)
    .then(() => { 
      console.log('I execute after'); 
      this.setState({ removing: false }); 
    }) 
    .catch(() => { 
      this.setState({ removing: false }); 
    }); 
}

内容的提问来源于stack exchange,提问作者HobbitOfShire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:05:26