有人能帮我解决这个问题吗?我正在尝试检索使用webrtc发送的数据量。但我无法理解这些承诺。
我需要遍历发送者列表,但对于每个发送者,我需要等待承诺,然后才能继续下一个发送者。
// Reset datacounter
Client.DataUsed = 0;
// Get senders (audio/video)
const senders = Client.WebcamConnection.getSenders();
// Iterate through senders
senders.forEach(sender => {
// Get the stats then await the promise using then
sender.getStats().then(stat => {
// Iterate through raports of stat
stat.forEach(report => {
// Check if is the right raport
if (report.type === 'outbound-rtp') {
// Add the byte count to the datacounter
Client.DataUsed += report.bytesSent + report.headerBytesSent;
}
});
});
});
// Do something with the Client.DataUsed发布于 2020-05-23 21:26:47
正如您所说,在所有承诺都确定之前,您不能使用结果。您可以使用Promise.all来等待它们,请参阅***注释:
// Reset datacounter
Client.DataUsed = 0;
// Get senders (audio/video)
const senders = Client.WebcamConnection.getSenders();
// ***Create an array of promises, one for each sender, and pass it into
// `Promise.all`***
Promise.all(senders.map(sender => {
// *** Return the promise created by `then` so `Promise.all` can
// wait for it***
// Get the stats then await the promise using then
return sender.getStats().then(stat => {
// Iterate through raports of stat
stat.forEach(report => {
// Check if is the right raport
if (report.type === 'outbound-rtp') {
// Add the byte count to the datacounter
Client.DataUsed += report.bytesSent + report.headerBytesSent;
}
});
});
})
.then(() => {
// Do something with the Client.DataUsed
})
.catch(error => {
// Handle/report error
});https://stackoverflow.com/questions/61972695
复制相似问题