首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在js promises中挣扎,foreach promises添加结果

在js promises中挣扎,foreach promises添加结果
EN

Stack Overflow用户
提问于 2020-05-23 21:22:41
回答 1查看 36关注 0票数 0

有人能帮我解决这个问题吗?我正在尝试检索使用webrtc发送的数据量。但我无法理解这些承诺。

我需要遍历发送者列表,但对于每个发送者,我需要等待承诺,然后才能继续下一个发送者。

代码语言:javascript
复制
// 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-23 21:26:47

正如您所说,在所有承诺都确定之前,您不能使用结果。您可以使用Promise.all来等待它们,请参阅***注释:

代码语言:javascript
复制
// 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
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61972695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档