【问题标题】:Wait for server response with axios from different file React等待来自不同文件 React 的 axios 的服务器响应
【发布时间】:2019-07-27 08:34:51
【问题描述】:

我有一个循环。在每一轮中,我都需要将 Question 数据添加到 MongoDB 数据库中。这工作正常。但是,我想在循环进入下一轮之前获取新插入的 Question_id。这是我有问题的地方。服务器返回 _id 之前需要一定的时间,然后循环进入下一轮。因此,我需要一种方法来等待服务器响应,然后才能进入下一轮循环。

这是我的后端代码:

router.post("/createQuestion", (req, res) => {
  const newQuestion = new Question({
    description: req.body.description,
    type: req.body.type, 
    model: req.body.model
  });
  newQuestion.save().then(question => res.json(question._id))
  .catch(err => console.log(err));
});

这是我的 axios 函数,它在一个单独的文件中并导入到类中:

export const createQuestion = (questionData) => dispatch => {
  axios.post("/api/scorecard/createQuestion", questionData)
    .then(res => {
      return res.data;
    }).catch(err =>
         console.log("Error adding a question")
    );
};

这是我课堂上的代码:

JSON.parse(localStorage.getItem(i)).map(question => {
      const newQuestion = {
        description: question.description,
        type: question.questionType,
        model: this.props.model
      }
       const question_id =  this.props.createQuestion(newQuestion);
       console.log(question_id);
}

控制台显示未定义

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    我遇到了同样的问题,我通过将数组问题发送到节点并逐一读取问题并使用下一个问题 ID 更新来解决了同样的问题。

    router.post("/createQuestion", (req, res) => {
    let d =[questionarray];
    let i = 0;
            let length = d.length;
            var result = [];
            try {
                const timeoutPromise = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));
                for (i = 0; i < length; i++) {
                    await timeoutPromise(1000);   // 1000 = 1 second
                    let CAT_ID = parseInt(d[i].CAT_ID);
                    let TOPIC_ID = parseInt(d[i].TOPIC_ID);
                    let Q_DESC = (d[i].Q_DESC);
                    let OPT_1 = (d[i].OPT_1);
                    let OPT_2 = (d[i].OPT_2);
                    let OPT_3 = (d[i].OPT_3);
                    let OPT_4 = (d[i].OPT_4);
                    let ANS_ID = (d[i].ANS_ID);
                    let TAGS = (d[i].TAGS);
                    let HINT = (d[i].HINT);
                    let LEVEL = d[i].LEVEL;
                    let SRNO = d[i].SrNo;
                    let qid;
    
                    const savemyData = async (data) => {
                        return await data.save()
    
                    }
                    var myResult = await Question.find({ TOPIC_ID: TOPIC_ID }).countDocuments(function (err, count) {
                        if (err) {
                            console.log(err);
                        }
                        else {
                            if (count === 0) {
                                qid = TOPIC_ID + '' + 10001;
                                const newQuestion = new Question({
                                    Q_ID: qid,
                                    CAT_ID: CAT_ID,
                                    TOPIC_ID: TOPIC_ID,
                                    Q_ID: qid,
                                    Q_DESC: Q_DESC,
                                    OPT_1: OPT_1,
                                    OPT_2: OPT_2,
                                    OPT_3: OPT_3,
                                    OPT_4: OPT_4,
                                    ANS_ID: ANS_ID,
                                    HINT: HINT,
                                    TAGS: TAGS,
                                    LEVEL: LEVEL,
                                    Q_IMAGE: ''
                                })
    
                                await savemyData(newQuestion)
                                    .then(result => { return true })
                                    .catch(err => { return false });
                                //`${SRNO} is added successfully`
                                //`${SRNO} is Failed`
    
                            }
    
                            else if (count > 0) {
                                //   console.log(count)
                                Question.find({ TOPIC_ID: TOPIC_ID }).sort({ Q_ID: -1 }).limit(1)
                                    .then(question => {
                                        qid = question[0].Q_ID + 1;
                                        const newQuestion = new Question({
                                            Q_ID: qid,
                                            CAT_ID: CAT_ID,
                                            TOPIC_ID: TOPIC_ID,
                                            Q_ID: qid,
                                            Q_DESC: Q_DESC,
                                            OPT_1: OPT_1,
                                            OPT_2: OPT_2,
                                            OPT_3: OPT_3,
                                            OPT_4: OPT_4,
                                            ANS_ID: ANS_ID,
                                            HINT: HINT,
                                            TAGS: TAGS,
                                            LEVEL: LEVEL,
                                            Q_IMAGE: ''
                                        })
                                        await savemyData(newQuestion)
                                            .then(result => { return true })
                                            .catch(err => { return false });
    
                                    })
                                    .catch(err => console.log(err));
                            }
                        }
                    });
                    if (myResult)
                        result.push(`${SRNO} is added successfully`);
                    else
                        result.push(`${SRNO} is Failed`);
                }
                //      console.log(result)
                return res.json(result);
            }
            catch (err) {
                //res.status(404).json({ success: false })
                console.log(err)
            }
    });
    

    【讨论】:

      【解决方案2】:

      首先,您的函数 createQuestion 不返回值,因此分配给 question_id 将始终未定义。无论如何,因为你在你的createQuestion 函数中有一个调度,我假设你使用redux,所以我建议你使用redux-thnk,将获取新动作逻辑拆分为一个 thunk 动作,并使用 questionID 值从redux 状态而不是从createQuestion 返回一个值。在您的班级中,您可以监听questionID 的更改,如果发生这种情况,请发送保存下一个问题。

      【讨论】:

      • 我已经编辑了我的代码,所以我的函数 createQuestion() 现在有一个返回值。你能建议我如何将这个值赋给我的变量吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多