我试图以角度重新排列标签顺序。我需要运行2个循环的原因是因为我使用的mongodb不允许重复值。因此,在第一个循环中,我将值重置为随机数,然后设置正确的顺序索引值。但是,当我尝试运行下面的代码时,它没有顺序执行。
updateTabsOrder(){
for(let i=0; i<this.rearrangedTabs.length; i++){
this._dataService.updateTabsOrder(this.rearrangedTabs[i].id, Math.random())
.subscribe((response) => {
console.log('a');
})
}
for(let i=0; i<this.rearrangedTabs.length; i++){
this._dataService.updateTabsOrder(this.rearrangedTabs[i].id, i+1)
.subscribe((response) => {
console.log('b');
})
}
}
服务
updateTabsOrder(tab_id, order_index){
return this.http.put(this.base_url + 'manufacturer_tabs/' + tab_id, {
order_index: order_index
})
.map(data => {
return data;
});
}
/ * JSON * /
[
{
"order_index": 2,
"tab_name": "tab 1",
"createdAt": "2018-04-24T12:46:41.890Z",
"updatedAt": "2018-04-24T14:38:05.138Z",
"manufacturers": "5acf62cf080d700c2209d40b",
"id": "5adf2731366e1a0e4085a4f3"
},
{
"order_index": 1,
"tab_name": "tab 2",
"createdAt": "2018-04-24T12:46:47.985Z",
"updatedAt": "2018-04-24T14:09:15.919Z",
"manufacturers": "5acf62cf080d700c2209d40b",
"id": "5adf2737366e1a0e4085a4f4"
}
]
以上代码输出为:
b
a
b
而不是
a
a
b
b
答案 0 :(得分:3)
您可以使用promise all等待第一批和第二批。为简单起见,我使用map()
。
async updateTabsOrder(){
// make sure that tabs is an Array and we can call .map
const rearrangedTabs = Array.from(this.rearrangedTabs);
// run the first batch of requests to the server
const randomizingPromises = rearrangedTabs.map(tab =>
this._dataService.updateTabsOrder(tab.id, Math.random()).toPromise()
);
// wait until all requests from the first batch to the server finish
await Promise.all(randomizingPromises).then(() => console.log("finished randomizing order"));
// run the second batch of requests to the server
const finalPromises = rearrangedTabs.map((tab, i) =>
this._dataService.updateTabsOrder(tab.id, i+1).toPromise()
);
// wait until all requests from the second batch to the server finish
await Promise.all(finalPromises).then(() => console.log("finished final order"));
console.log("finished all");
}
这将分两步进行评估:
答案 1 :(得分:-2)
Javascript它是一种异步语言。
updateTabsOrder() {
this.rearrangedTabs.map((item, index, object) => {
console.log(item.id + ' ' + (index + 1));
this._dataService.updateTabsOrder(item.id, Math.random())
.subscribe((response) => {
console.log('a');
});
return item;
}).map((item, index, object) => {
console.log(item.id + ' ' + (index + 1));
this._dataService.updateTabsOrder(item.id, index + 1)
.subscribe((response) => {
console.log('b');
});
return item;
});
}