node.js - 如何在 Sequelize 中获得超出 promise 的结果?

标签 node.js sequelize.js

var mark = 0;
var rightAns=0;
var wrongAns = 0 ;
var notAttempt=0;

questionId = ['1', '2', '3','4', '5', '6','7', '8', '9']

answer = [ 'B', 'D', 'C','E', 'E', 'E', 'E', 'E', 'E']

for(let i = 0 ; i<questionId.length ; i++){

    if(answer[i]==='E'){
      notAttempt +=1; 
    }

else{

    Questions.findOne({where:{id: questionId[i]}})
     .then(question=>{

         if(answer[i]===question.answer){
          rightAns+=1; 
         }else{ 
          wrongAns+=1;
         }

    }) 
   }

 };

最佳答案

您可以使用异步/等待模式。

 var mark = 0;
  var rightAns = 0;
  var wrongAns = 0;
  var notAttempt = 0;

  let questionId = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

  let answer = ["B", "D", "C", "E", "E", "E", "E", "E", "E"];

  for (let i = 0; i < questionId.length; i++) {
    if (answer[i] === "E") {
      notAttempt += 1;
    } else {
      let question = await Questions.findOne({ where: { id: questionId[i] } });
      if (answer[i] === question.answer) {
        rightAns += 1;
      } else {
        wrongAns += 1;
      }
    }
  }

在您的 Controller 中(在问题的所有者评论之后):
 exports.postAnswerEvaluate = async (req, res, next) => {
  try {
    const answer = req.body.answer; //will get answer = ["B", "D", "C", "E", "E", "E", "E", "E", "E"];
    const questionId = req.body.questionId; //will get questionId = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];}

    var mark = 0;
    var rightAns = 0;
    var wrongAns = 0;
    var notAttempt = 0;

    // let questionId = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

    // let answer = ["B", "D", "C", "E", "E", "E", "E", "E", "E"];

    for (let i = 0; i < questionId.length; i++) {
      if (answer[i] === "E") {
        notAttempt += 1;
      } else {
        let question = await Questions.findOne({
          where: { id: questionId[i] }
        });
        if (answer[i] === question.answer) {
          rightAns += 1;
        } else {
          wrongAns += 1;
        }
      }
    }
  } catch (exc) {
    // handle exceptions here
  }
};

关于node.js - 如何在 Sequelize 中获得超出 promise 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61848295/

相关文章:

JavaScript 在 Node.js 中无法获取函数返回值

node.js - 将 javascript 与 node.js 和 pug 混合

mysql - 序列化涉及 "last inserted row id"的特殊查询

javascript - 无法在 node-cron 调度方法中获取数据

node.js - 为每个 findall Sequelize findall 是可能的吗?

node.js - 序列化事务总是返回 null

javascript - jQuery 发现在 Node.js 中无法正常工作

node.js - NodeJS Sequelize : Issue with setting value of associations

node.js - Webpack Node 全局模块

sequelize.js - 如何使用 mySQL 在 sequelize 中定义和使用地理点