我有一个对象/字符串数组。
this.addtenant().subscribe(r => {
let a = ['plant1', 'plant2'];
for (let b of a) {
this.myService.saveAllData(b).subscribe(r => {
console.log("result" r);
});
}
});
并且 getAllData 位于 myservice 文件中,它返回一个 Observable。
saveAlldata(b) {
this.http.post(url,b);
}
问题是因为我使用的是订阅,所以调用是异步的,我希望它是这样的: 第一个“plant1”后调用必须完成,然后必须进行 plant2。简而言之,同步调用。
最佳答案
我认为你应该使用 async/await 进行同步调用。
这是教程之一: https://www.techiediaries.com/javascript-async-await-tutorial/
示例代码演示类似于:
responseArr: any[] = [];
func1()
let x = [1,2,3];
func2(x);
}
async func2(arr) { // make the function async
for(let i=0; i<arr.length ; i++){
const response: any = await this.myService(arr[i]); // wait on each service call. This will give synchronous behaviour
this.handleResponse(response); // handle response in a function if there is common functionality in each response
}
reuturn responseArr; // return the final response
}
handleResponse(response) {
responseArr.push(response);
}
关于javascript - 在 for 循环中制作同步 Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61055040/