首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >语句未按预期执行。

语句未按预期执行。
EN

Stack Overflow用户
提问于 2019-06-28 07:50:15
回答 2查看 166关注 0票数 0

我正在编写代码,从api中获取数据并将其保存在mongodb数据库中。我所写的代码是:

代码语言:javascript
复制
     getSquadList: async (ctx) => {
var query = ctx.request.query;
var squadList = await getSquadsOfMatch(query.matchId);
if (squadList.length <= 1) {
  var response = await axios.get(
    `${strapi.config.currentEnvironment.getSquadListApi}?apikey=${strapi.config.currentEnvironment.cricApiKey}&unique_id=${query.matchId}`
  );

  squadList = response.data.squad;

  var match = await Match.findOne({
    unique_id: query.matchId
  });

  var team1Squad, team2Squad;

  await squadList.forEach(async squad => {
    if (squad.name === match['team-1']) {
      team1Squad = {
        name: match['team-1'],
        match_id: match['unique_id'],
        match: match['_id'],
      };

      await new Squad(team1Squad).save();
      console.log('1');
    } else if (squad.name === match['team-2']) {
      team2Squad = {
        name: match['team-2'],
        match_id: match['unique_id'],
        match: match['_id'],
      };

      await new Squad(team2Squad).save();
      console.log('2');
    }
  });

  squadList = await getSquadsOfMatch(query.matchId);
  console.log('3');
}
ctx.send(squadList);
      }

我使用了console.log()来查看执行顺序。我想要的顺序是12,3,但实际的输出是3,12,如何使程序在最后执行这些行。squadList =等待getSquadsOfMatch(query.matchId);console.log('3');

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-28 08:17:12

如果我们模仿async函数与forEach一起使用forEach,则不能将它与forEach一起使用:

代码语言:javascript
复制
function forEach(arr, callback){
   for(let i=0;i<arr.length;i++){
        callback(arr[i], i, arr);
   }
}

正如您所看到的,它不会await您的async回调。

您可以创建一个自定义forEach,如:

代码语言:javascript
复制
async function forEach(arr, callback){
   for(let i=0;i<arr.length;i++){
        await callback(arr[i], i, arr);
   }
}

或者使用简单的for循环。

另外,您可以做的是将所有的承诺推送到一个数组中,并调用Promise.all来处理所有请求。

代码语言:javascript
复制
async (ctx) => {
    var query = ctx.request.query;
    var squadList = await getSquadsOfMatch(query.matchId);
    if (squadList.length <= 1) {
        var response = await axios.get(
            `${strapi.config.currentEnvironment.getSquadListApi}?apikey=${strapi.config.currentEnvironment.cricApiKey}&unique_id=${query.matchId}`
        );

        squadList = response.data.squad;

        var match = await Match.findOne({
            unique_id: query.matchId
        });

        var team1Squad, team2Squad;
        const promises = squadList.map(squad => {
            if (squad.name === match['team-1']) {
                team1Squad = {
                    name: match['team-1'],
                    match_id: match['unique_id'],
                    match: match['_id'],
                };
                console.log('1');
                return new Squad(team1Squad).save(); //returning the promise
            } else if (squad.name === match['team-2']) {
                team2Squad = {
                    name: match['team-2'],
                    match_id: match['unique_id'],
                    match: match['_id'],
                };
                console.log('2');
                return new Squad(team2Squad).save(); //returning the promise
            }
        });
        await Promise.all(promises); //making all the changes parallely

        squadList = await getSquadsOfMatch(query.matchId);
        console.log('3');
    }
    ctx.send(squadList);
}

注意:--我写了一篇关于循环和异步函数的文章,您可以随意查看,https://medium.com/trappedpanda/loops-asynchronous-functions-and-returning-collective-results-in-node-js-b7566285fb74

票数 2
EN

Stack Overflow用户

发布于 2019-06-28 07:59:34

您可以创建一个必须首先执行的承诺数组,并在运行Promise.all之前等待它们使用getSquadsOfMatch进行解析。

代码语言:javascript
复制
getSquadList: async (ctx) => {
    var query = ctx.request.query;
    var squadList = await getSquadsOfMatch(query.matchId);
    if (squadList.length <= 1) {
      var response = await axios.get(
        `${strapi.config.currentEnvironment.getSquadListApi}?apikey=${strapi.config.currentEnvironment.cricApiKey}&unique_id=${query.matchId}`
      );

      squadList = response.data.squad;

      var match = await Match.findOne({
        unique_id: query.matchId
      });

      var team1Squad, team2Squad;

      const tasks = squadList.map(async squad => {
        if (squad.name === match['team-1']) {
          team1Squad = {
            name: match['team-1'],
            match_id: match['unique_id'],
            match: match['_id'],
          };

          await new Squad(team1Squad).save();
          console.log('1');
        } else if (squad.name === match['team-2']) {
          team2Squad = {
            name: match['team-2'],
            match_id: match['unique_id'],
            match: match['_id'],
          };

          await new Squad(team2Squad).save();
          console.log('2');
        }
      });

      await Promise.all(tasks)
      squadList = await getSquadsOfMatch(query.matchId);
      console.log('3');
    }
    ctx.send(squadList);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56802949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档