简体   繁体   English

如何解决我的异步功能?

[英]How can I solve my asynchronous function?

I want to get the number of users for each shop in my database. 我想在数据库中获取每个商店的用户数。 So I'm making two call in my Db, one for the shop and another for the users. 因此,我在Db中打了两个电话,一个打给商店,另一个打给用户。 And I have a problem I don't have anything in my "nbr_users" return value.. Could you help ? 而且我有一个问题,我的“ nbr_users”返回值中没有任何内容。

function nbr_users(key) {
    return new Promise((resolve, reject) => {
        db.User.find({
            shop: key
        }, (err, users) => {
            if (err) reject(err)
            else {
                resolve(users.length) // Maybe my problem is here...
            }
        })
    })
}

module.exports = (req, res) => {
    db.Account.find({},
    (err, accounts) => {
        if (err) res.json(err)
        else {
            var accountMap = {}
            var i = 0;
            accounts.forEach(async function(account) {
                accountMap[i++] = {
                    users: await nbr_users(account.key) // the value I want
                }
              });
            res.json({user_list: accountMap})
        }
    })
}

You have something returning from your nbr_users(key) . 您从nbr_users(key)返回了一些东西。 You have a promise, then you may use .then . 您有一个承诺,那么您可以使用.then

Because you are in a loop with async. 因为您处于异步循环中。 functions and you don't want to lose track of i I'd recomend you to use anonymous Immediately-invoked function expression . 功能,你不想失去跟踪的i我会建议更换您使用匿名立即调用的函数表达式

function(i){
    nbr_users(account.key).then(function(length){
      accountMap[i] = {
        users: length
    })
}(i++);
accounts.forEach(async function(account) {
            accountMap[i++] = {
                users: await nbr_users(account.key) // the value I want
            }
          });

Should be more like 应该更像

var accountMap = {}
var i = 0;
for (let account of accounts) {
   let users = await nbr_users(account.key);
   accountMap[i++] = {
                users: users
            }
}

res.json({user_list: accountMap});

Make sure you're running that in an async function. 确保您正在async功能中运行它。

Downside of this way is that each subsequent nbr_users(account.key) request must wait for the previous one. 这种方式的缺点是每个后续nbr_users(account.key)请求都必须等待前一个请求。 There is a way to run them all without each one waiting for the previous as well, let me know if you want me to show that way -- it's slightly more complicated 有一种方法可以全部运行而无需等待每个人,让我知道是否要我显示这种方式-稍微复杂一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM