【问题标题】:How to use Promise with nested foreach如何将 Promise 与嵌套的 foreach 一起使用
【发布时间】:2020-06-27 13:57:27
【问题描述】:

我在嵌套的 foreach 循环中找到所有用户的钱包,但我无法弄清楚在哪里使用 resolve() 进行返回回调,

function genwallets() {
    return new Promise((resolve, reject) => {
    var i = 0;
    try {
        db.users.findAll({}).then((users)=>{
            db.supportedTokens.findAll({}).then((tokens)=>{ 
                users.forEach(function(user) {
                    tokens.forEach(function(token) {
                    db.wallets.findOne({where:{userId: user['id'], supportedTokenId: token['id']}}).then((wallet)=>{
                        console.log(JSON.stringify(wallet));
                    })
                    });
                });
            })
        });

    } catch (err) {
        console.log(err);
    }
});
}

【问题讨论】:

标签: javascript node.js express sequelize.js


【解决方案1】:

forEach 不适用于承诺。使用for...ofPromise.all 之类的东西

function genwallets() {
  return new Promise((resolve, reject) => {
    var i = 0;
    try {
      db.users.findAll({}).then(users => {
        db.supportedTokens.findAll({}).then(tokens => {
          for(const user of users) {
            for(const token of tokens) {
              db.wallets
                .findOne({
                  where: { userId: user["id"], supportedTokenId: token["id"] }
                })
                .then(wallet => {
                  console.log(JSON.stringify(wallet));
                });
            }
          }
        });
      });
    } catch (err) {
      console.log(err);
    }
  });
}

顺便说一句,你不需要将它包装在 promise 中。

您可以使用async/await 简化此操作

async function genwallets() {
  const users = await db.users.findAll({});
  const tokens = await db.supportedTokens.findAll({});

  for(const user of users) {
    for(const token of tokens) {
      const wallet = await db.wallets
        .findOne({
          where: { userId: user["id"], supportedTokenId: token["id"] }
        });
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多