挣扎与js承诺,foreach承诺添加结果

有人可以帮助我解决这个问题,我正在尝试检索通过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
评论
哎呀呀o
哎呀呀o

As you say, you can't use the results until all the promises are settled. You can use Promise.all to wait for them, see *** comments:

// 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
});
点赞
评论