如何让我的代码按顺序运行?例如,
如果我有一个从服务获取一些数据的 for 循环,我希望
n+1
迭代仅在nth
迭代完成后运行.我希望循环后的代码仅在 for 循环完成所有交互后才执行。
Example code:
someMethod() {
for ( var i = 0; i < someLength; i++) {
// get some data
this.dataService.get(i).subscribe(data => {
// do something with the data
});
}
//
console.log ('print me only after all iterations');
// ....
// some more lines of code
}
Here is another example ( Plunker ) :
someMethod() {
for ( var i = 0; i < 5; i++) {
setTimeout(()=> {
console.log('This is iteration' + i);
},500);
}
// I want to execute this line of code only after the
// for loop has completed all iterations.
console.log ('print me only after all iterations');
// ....
// some more lines of code
}
有什么想法吗?
最佳答案
您可以将每个迭代包装在一个 Promise 中并等待它:
async function someMethod() {
for (var i = 0; i < 5; i++) {
await new Promise(resolve => {
setTimeout(()=> {
console.log('This is iteration ' + i);
resolve();
}, 500);
});
}
console.log ('print me only after all iterations');
}
someMethod();
关于angular - Angular/ typescript 中的顺序代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649315/