【问题标题】:Promise.all with axios / node.jsPromise.all 与 axios / node.js
【发布时间】:2021-01-01 05:17:30
【问题描述】:

我有点卡在这里试图等待来自两个或多个 axios 承诺的结果以进一步处理它们。 console.log("测试");在其他方法调用完全执行之前执行。我觉得我设置递归解析的方式不正确,但不确定要调整什么。这里有人有想法吗?非常感谢。

输出---

test
Mon Sep 14 2020 14:04:37 GMT+0100 (Irish Standard Time) - 2020-09-13T00:00:00Z - 2020-09-14T00:00:00Z - 0 - 14897 - 1000
Mon Sep 14 2020 14:04:37 GMT+0100 (Irish Standard Time) - 6 - 3247395

索引---

Promise.all([
  vault.collectAuditTrailHistory('document_audit_trail', startDate, endDate),
  vault.collectGroupMembers(6)
]).then(result => {
  console.log("test");
})

保险库类---

async login() {
        return this.axiosInstance
            .post('/api/v20.2/auth', 'username=' + this.username + '&password=' + this.password, this.config)
            .then(response => {
                if (response.data.responseStatus = "SUCCESS") {
                    this.axiosInstance.defaults.headers.common['Authorization'] = response.data.sessionId;
                }
            })
            .catch(error => console.error(error));
    }

    async collectAuditTrailHistory(audittrail, startDate, endDate) {
        // check valid login
        if (this.isLoggedIn()) {
            return this.axiosInstance
                .get('/api/v20.2/audittrail/'+ audittrail +'?start_date=' + startDate + '&end_date=' + endDate + '&limit=1', this.config)
                .then(response => {
                    this.parseAuditTrailHistoryPage(audittrail, startDate, endDate, 0, response.data.responseDetails.total, 1000);
                })
                .catch(error => console.error(error));
        } else {
            return this.login()
                .then((response) => {
                    this.collectAuditTrailHistory(audittrail, startDate, endDate);
                });
        }
    }

    async collectGroupMembers(groudId) {
        // check valid login
        if (this.isLoggedIn()) {
            return this.axiosInstance
                .get('/api/v20.2/objects/groups/' + groudId, this.config)
                .then(response => {
                    for(let i = 0; i < response.data.groups[0].group.members__v.length; i++){ 
                        this.collectUserName(groudId, response.data.groups[0].group.members__v[i]);
                    }
                })
                .catch(error => console.error(error));
        } else {
            return this.login()
                .then((response) => {
                    return this.collectGroupMembers(groudId);
                });
        }
    }

    async collectUserName(groudId, userId) {
        // check valid login
        if (this.isLoggedIn()) {
            return this.axiosInstance
                .get('/api/v20.2/objects/users/' + userId, this.config)
                .then(response => {
                    console.log(new Date() + " - " + groudId + " - " + userId);
                    this.groupMembers.push([groudId,response.data.users[0].user.user_name__v]);
                })
                .catch(error => console.error(error));
        } else {
            return this.login()
                .then((response) => {
                    return this.collectUserName(groudId, userId);
                });
        }
    }

    isLoggedIn() {
        if (!this.axiosInstance.defaults.headers.common['Authorization'] || !this.lastTxnDateTime)
            return false;
        else {
            let diff = Math.abs(new Date() - this.lastTxnDateTime);
            if (Math.floor((diff/1000)/60) < 15) {
                return true;
            }
            else {
                return false;
            }
        }
    }

    async parseAuditTrailHistoryPage(audittrail, startDate, endDate, offset, total, limit) {
        console.log(new Date() + " - " + startDate + " - " + endDate + " - " + offset + " - " + total + " - " + limit);
        return this.axiosInstance
            .get('/api/v20.2/audittrail/' + audittrail + '?start_date=' + startDate + '&end_date=' + endDate + '&limit=' + limit + '&offset=' + offset, this.config)
            .then(response => {
                if ((offset+limit) < total) {
                    this.auditTrailHistory = this.auditTrailHistory.concat(response.data.data);
                    this.parseAuditTrailHistoryPage(audittrail, startDate, endDate, (offset+limit+1), total, limit);                    
                }
                else {
                    this.auditTrailHistory = this.auditTrailHistory.concat(response.data.data);
                }
            })
            .catch(error => console.error(error));
    }

【问题讨论】:

    标签: node.js promise axios


    【解决方案1】:

    我认为您在then 中缺少一些return

        async parseAuditTrailHistoryPage(audittrail, startDate, endDate, offset, total, limit) {
            console.log(new Date() + " - " + startDate + " - " + endDate + " - " + offset + " - " + total + " - " + limit);
            return this.axiosInstance
                .get('/api/v20.2/audittrail/' + audittrail + '?start_date=' + startDate + '&end_date=' + endDate + '&limit=' + limit + '&offset=' + offset, this.config)
                .then(response => {
                    if ((offset+limit) < total) {
                        this.auditTrailHistory = this.auditTrailHistory.concat(response.data.data);
    
                        // return promise (add it to the end of the  promise chaine)
                        return this.parseAuditTrailHistoryPage(audittrail, startDate, endDate, (offset+limit+1), total, limit);                    
                    }
                    else {
                        this.auditTrailHistory = this.auditTrailHistory.concat(response.data.data);
                    }
                })
                .catch(error => console.error(error));
        }
    

    如果没有修复,parseAuditTrailHistoryPage 将不会等待内部 parseAuditTrailHistoryPage 解决。修复后,递归的每次迭代都将等待下一次迭代直到最后一次(当(offset+limit) &lt; total == false).

    collectUserNamecollectAuditTrailHistory 中的同样问题,

    【讨论】:

    • 嗨@Daniel,非常感谢您的及时回复。你是对的,我能够根据你的 collectAuditTrailHistory 的 cmets 修复它,但不知何故我正在努力将它添加到 collectGroupMembers 中。如果我在循环中添加一个返回,例如return this.collectUserName(groudId, response.data.groups[0].group.members__v[i]);,它会中断循环并且只捕获一个用户。你可能知道如何调整它?
    • 我想通了 - let promises = []; for (let i = 0; i &lt; response.data.groups[0].group.members__v.length; i++) { promises.push(this.collectUserName(groudId, response.data.groups[0].group.members__v[i])); } return Promise.all(promises);
    • return Promise.all(response.data.groups[0].group.members__v.map(member =&gt; this.collectUserName(groudId, member)));
    猜你喜欢
    • 2020-09-24
    • 2020-08-02
    • 1970-01-01
    • 2020-08-16
    • 2016-11-20
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多