您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Node.js异步请求在Redis中进行循环

使用Node.js异步请求在Redis中进行循环

您有两个主要问题。

您的phoneNumber变量将不是您想要的变量。可以通过更改 数组的.forEach().map()迭代来解决此问题,因为这将为当前变量创建局部函数作用域。

您已经创建了一种方法来知道所有异步操作何时完成。有很多重复的问题/答案显示了如何执行此操作。您可能要使用Promise.all()

我建议这种解决方案利用您已经拥有的承诺:

function getContactList(contacts) {
    var contactList = {};
    return Promise.all(contacts.filter(utils.isValidNumber).map(function(phoneNumber) {
        return db.client().get(phoneNumber).then(function(reply) {
            // build custom object
            constactList[phoneNumber] = reply;
        });
    })).then(function() {
        // make contactList be the resolve value
        return contactList;
    });
}

getContactList.then(function(contactList) {
    // use the contactList here
}, funtion(err) {
    // process errors here
});

运作方式如下:

Node 2022/1/1 18:16:25 有287人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶