Nodejs等待/异步问题

时间:2019-11-26 12:19:29

标签: node.js async-await

我在NodeJ中执行函数时遇到问题。

我想等待函数中的每个promise,因为它根本没有等待,并且我的值不正确。

async function DistribToken(campid) {
    console.log("DEBUT");
     Campaign.findOne({ campid: campid }).then(
      (campaign) => {
        console.log(campaign);
        if (campaign.tokensend < campaign.nbuser) {
          console.log('Recherche de token');
           User.find().then(
            (user) => {
              len = user.length;
              console.log(len);
              for (var i = 0; i < len; i++) {
                console.log("VERIF TOKEN " + user[i].userid);
                  VerifToken(campid, user[i].userid);
              }
            })
        }else{
          console.log("MAX TOKEN SEND REACHED");
        }
      })
  }


  async function StartToken() {
    Campaign.find().then(
      (campaign) => {
        len = campaign.length;
        for (var i = 0; i < len; i++) {
          console.log("ANALYZE CAMPAIGN : " + campaign[i].campid + ' ' + campaign[i].campname)
          if (campaign[i].status === 'AC') {
            console.log("CAMPAIGN ACTIVE : " + campaign[i].campid + ' ' + campaign[i].campname + ': Start Distrib')
             DistribToken(campaign[i].campid);
          }
        }
      }
    ).catch(
      (error) => {
        res.status(400).json({
          error: error
        });
      }
    );
  }

但是它会在启动Veriftoken之前对所有用户DistribToken执行

我希望它

开始分发->分发令牌用户1->验证令牌用户1->分发令牌用户2 ...

有人对我的问题有答案吗? :)

2 个答案:

答案 0 :(得分:0)

在异步函数中,您可以等待诺言,因此可以用try catch块替换.then和.catch。您可以使用await关键字等待,直到承诺解决为止。

但这可能不是问题。我认为问题是您不等待DistribToken和VerifToken(我认为VerifToken也是异步函数吗?)。

async function DistribToken(campid) {
    try {
        let campaign = await Campaign.findOne({ campid: campid });
        console.log(campaign);
        if (campaign.tokensend < campaign.nbuser) {
            console.log('Recherche de token');
            let user = await User.find();
            const len = user.length;
            console.log(len);
            for (var i = 0; i < len; i++) {
                console.log("VERIF TOKEN " + user[i].userid);
                VerifToken(campid, user[i].userid); // you should probably await here too but i don't know if VerifToken returns a Promise
            }
        }
        else {
            console.log("MAX TOKEN SEND REACHED");
        }
    }
    catch (e) {
        console.error(e);
    }
}


async function StartToken() {
    try {
        let campaign = await Campaign.find();

        const len = campaign.length;
        for (var i = 0; i < len; i++) {
            console.log("ANALYZE CAMPAIGN : " + campaign[i].campid + ' ' + campaign[i].campname);
            if (campaign[i].status === 'AC') {
                console.log("CAMPAIGN ACTIVE : " + campaign[i].campid + ' ' + campaign[i].campname + ': Start Distrib');
                await DistribToken(campaign[i].campid);
            }
        }

    }
    catch (error) {
        res.status(400).json({
            error: error
        });
    }
}

我希望这会有所帮助,祝你好运!如果不清楚,请在下面评论。

答案 1 :(得分:0)

我正在更新您的代码,您可以尝试

async function DistribToken(campid) {
    try {


        console.log("DEBUT");
        let campaign = await Campaign.findOne({ campid: campid }).lean()
        console.log(campaign);
        if (campaign.tokensend < campaign.nbuser) {
            console.log('Recherche de token');
            let user = await User.find().lean()
            len = user.length;
            console.log(len);
            for (var i = 0; i < len; i++) {
                console.log("VERIF TOKEN " + user[i].userid);
                VerifToken(campid, user[i].userid);  // check this needs to be await or not
            }

        } else {
            console.log("MAX TOKEN SEND REACHED");
        }
    } catch (error) {
        console.error(error);
    }

}


async function StartToken() {
    try {
        let campaign = await Campaign.find().lean()
        len = campaign.length;
        for (var i = 0; i < len; i++) {
            console.log("ANALYZE CAMPAIGN : " + campaign[i].campid + ' ' + campaign[i].campname)
            if (campaign[i].status === 'AC') {
                console.log("CAMPAIGN ACTIVE : " + campaign[i].campid + ' ' + campaign[i].campname + ': Start Distrib')
                await DistribToken(campaign[i].campid); 
            }
        }
    } catch (error) {
        res.status(400).json({
            error: error
        });
    }

}