我有两个几乎完全相同的方法,只是其中一个是异步的,并返回一个promise,它解析了回调方法返回的promise,另一个不是。这2个函数实际上是相同的,但由于回调是在循环中调用的,所以我还不知道如何在等待所有promise的解析时提取公共部分。有什么建议吗?
iterate(callback) {
let firstIteration = true;
let lastIp;
while (lastIp = (firstIteration && this.startingIp ? this.startingIp : this.subnet.nextIp(lastIp))) {
firstIteration = false;
callback(lastIp, this.subnet.buildProgressData(lastIp));
}
}
async iterateAsync(callback) {
let firstIteration = true;
let lastIp;
while (lastIp = (firstIteration && this.startingIp ? this.startingIp : this.subnet.nextIp(lastIp))) {
firstIteration = false;
await callback(lastIp, this.subnet.buildProgressData(lastIp));
}
}
答案 0 :(得分:2)
只需为您的实例编写一个迭代器而不是带回调的[Symbol.iterator]*() {
let firstIteration = true;
let lastIp;
while (lastIp = (firstIteration && this.startingIp ? this.startingIp : this.subnet.nextIp(lastIp))) {
firstIteration = false;
yield [lastIp, this.subnet.buildProgressData(lastIp)];
}
}
iterate(callback) {
for (const [ip, progress] of this)
callback(ip, progress);
}
async iterateAsync(callback) {
for (const [ip, progress] of this)
await callback(ip, progress);
}
方法,这样调用者就可以决定如何使用它。
iterate
您可能根本不需要这些for … of
方法,使用[Symbol.iterator]*() {
let ip;
if (ip = this.startingIp)
yield this.startingIp;
while (ip = this.subnet.nextIp(ip))
yield [ip, this.subnet.buildProgressData(ip)];
}
要简单得多。
使用生成器功能,您还可以轻松简化逻辑
@EnableEurekaClient
public class UserServiceApplication extends WebMvcConfigurer{