如何在for循环内等待响应?

编程入门 行业动态 更新时间:2024-10-24 14:17:18
本文介绍了如何在for循环内等待响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

描述:我在for循环中调用了HTTP请求.我想从服务文件中获取响应,然后增加循环.如何等待从服务文件中获取响应,然后执行循环. >

Description : I called an HTTP request inside for loop.I want to get the response from service file then increase loop.How can i wait to get response from service file then execute loop.

for(let i=0;i<final_arr.length;i++) { this.user.list_upload(JSON.stringify(ins_arr)).subscribe(data=>{ if(data.hasOwnProperty('STATUS')) { if(data.STATUS.toLowerCase()=='success') { this.update(); } else if(data.STATUS.toLowerCase() == 'error') { this.user.showToast(data.MESSAGE); } } },err=>{ this.user.showToast("Error occurred in service file"); }); }

请告知

推荐答案

您应使用异步功能.首先将HTTP请求转换为一个Promise,然后在for循环内异步调用该Promise:

You should use an async function. First convert the HTTP request to a promise, then call that promise asynchronously inside the for loop:

asyncReq (){ return new Promise((resolve, reject) => { this.user.list_upload(JSON.stringify(ins_arr)).subscribe(data=>{ if(data.hasOwnProperty('STATUS')){ if(data.STATUS.toLowerCase()=='success') { this.update(); resolve(); } else if(data.STATUS.toLowerCase() == 'error') { this.user.showToast(data.MESSAGE); reject(); } } },err=>{ this.user.showToast("Error occurred in service file"); reject(err); }); }) } //Async function where loop progresses only after asyncReq completes async asyncForFunction () { for(let i=0; i < final_arr.length; i++){ await this.asyncReq (); } }

更多推荐

如何在for循环内等待响应?

本文发布于:2023-08-07 18:17:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1320835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!