How to wait for response inside for loop?(如何在 for 循环中等待响应?)
问题描述
说明:我在for循环中调用了一个HTTP请求.我想从服务文件中获取响应然后增加循环.我如何等待从服务文件中获取响应然后执行循环.
for(let i=0;i<块引用>
请指教
你应该使用异步函数.首先将 HTTP 请求转换为 Promise,然后在 for 循环中异步调用该 Promise:
asyncReq (){return new Promise((resolve, reject) => {this.user.list_upload(JSON.stringify(ins_arr)).subscribe(data=>{if(data.hasOwnProperty('STATUS')){if(data.STATUS.toLowerCase()=='成功'){this.update();解决();}否则 if(data.STATUS.toLowerCase() == 'error'){this.user.showToast(data.MESSAGE);拒绝();}}},错误=>{this.user.showToast("服务文件出错");拒绝(错误);});})}//异步函数,其中循环仅在 asyncReq 完成后进行异步 asyncForFunction () {for(让 i=0; i < final_arr.length; i++){等待 this.asyncReq ();}}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");
});
}
Please advise
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 循环中等待响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 for 循环中等待响应?
基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
