私はminheap.heapList
の長さを編集するいくつかのロジックをしようとしています。私はかなりPromises
に新しいですので、私はこれにどのようにアプローチするか分かりません。 while loop
の中で私はasync
の機能も同様に呼び出す予定です。競合状態を適切に処理する方法が不明確約束の.then()内にループwhile
let minheap = new MinHeap();
let i = 0;
Promise.all(logSources.map(logSource => {
logSource.popAsync().then(log => {
minheap.insert({
ts: log.date.getTime(),
source: i++,
data: log
})
});
i += 1;
})).then(
while(minheap.heapList.length) {
...
// async logic
...
}
);
これは、同期コードを非同期に変換しようとすることです。同期コードの.pop()
は.popAsync()
に置き換えてpromise
を返します。ここで
が同期ロジックです:
const lenLogSources = logSources.length;
let minheap = new MinHeap();
for (let i = 0; i < lenLogSources; i++) {
let log = logSources[i].pop();
minheap.insert({
ts: log.date.getTime(),
source: i,
data: log
})
}
while (minheap.heapList.length) {
let heapNode = minheap.popMin();
let currTimestamp = heapNode['ts'];
printer.print(heapNode.data);
let nextMinTimestamp = minheap.getPeakTimestamp();
while (currTimestamp <= nextMinTimestamp) {
let log = logSources[heapNode['source']].pop();
if (log) {
let logtime = log.date.getTime();
if (logtime <= nextMinTimestamp) {
printer.print(log);
currTimestamp = logtime;
} else {
minheap.insert({
ts: logtime,
source: heapNode["source"],
data: log
});
break;
}
} else {
heapNode = minheap.popMin();
printer.print(heapNode.data);
currTimestamp = heapNode['ts'];
if (minheap.heapList.length) {
nextMinTimestamp = minheap.getPeakTimestamp();
} else {
while (true) {
let m = logSources[heapNode['source']].pop();
if (m) {
printer.print(m);
} else {
console.log('Drained: ' + heapNode['source']);
break;
}
}
break;
}
}
}
}
a)コールバックを 'then'に渡す必要があります。ループ構造ではありません。b)非同期ロジックの周りに' while'ループを使用することはできません。代わりに再帰的なアプローチを使用してください。 – Bergi