Vue 2方法中不使用Promise.all处理双API调用并存储结果
问题分析
你当前代码的核心问题在于:
resultOne和resultTwo存储的是Promise对象,而非API返回的实际结果;且你在then回调里仅打印结果,没有将结果存入可全局访问的变量。- 异步请求未完成就执行了
console.log和this.Loading = false,此时API还未返回数据,自然拿不到有效结果。
以下是不使用Promise.all的两种可行实现方案:
方案一:串行调用(先完成第一个请求再执行第二个)
适合两个请求有依赖关系的场景,或不需要并行发起的情况:
<script> export default { data() { return { Loading: false, resultOne: null, resultTwo: null, dateRange: [] // 你的日期范围数据 } }, methods: { apiCall() { this.Loading = true; // 先发起第一个API请求 get('lots/path1', { locationId: '9047695746459876', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then(result => { this.resultOne = result; console.log(result, 'result 1'); // 第一个请求完成后,发起第二个请求 return get('lots/path2', { locationId: '897349823749237', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }); }).then(result => { this.resultTwo = result; console.log(result, 'result 2'); // 两个请求都完成后,调用处理方法 this.handleResults(); this.Loading = false; }).catch(err => { console.error('请求出错', err); this.Loading = false; }); }, handleResults() { // 在这里处理两个结果,或传递给其他方法 console.log('最终结果:', this.resultOne, this.resultTwo); // this.anotherMethod(this.resultOne, this.resultTwo); } } } </script>
方案二:并行调用,通过状态判断完成时机
适合两个请求无依赖、需要同时发起的场景:
<script> export default { data() { return { Loading: false, resultOne: null, resultTwo: null, dateRange: [] // 你的日期范围数据 } }, methods: { apiCall() { this.Loading = true; // 重置结果状态 this.resultOne = null; this.resultTwo = null; // 发起第一个API请求 get('lots/path1', { locationId: '9047695746459876', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then(result => { this.resultOne = result; console.log(result, 'result 1'); // 检查是否两个请求都已完成 this.checkAndHandle(); }).catch(err => { console.error('第一个请求出错', err); this.Loading = false; }); // 发起第二个API请求 get('lots/path2', { locationId: '897349823749237', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then(result => { this.resultTwo = result; console.log(result, 'result 2'); // 检查是否两个请求都已完成 this.checkAndHandle(); }).catch(err => { console.error('第二个请求出错', err); this.Loading = false; }); }, checkAndHandle() { // 只有两个结果都获取到,才执行后续逻辑 if (this.resultOne !== null && this.resultTwo !== null) { this.handleResults(); this.Loading = false; } }, handleResults() { // 在这里处理结果,或传递给其他方法 console.log('最终结果:', this.resultOne, this.resultTwo); // this.anotherMethod(this.resultOne, this.resultTwo); } } } </script>
内容的提问来源于stack exchange,提问作者user17206275
相关产品推荐
相关产品推荐

