0

I did below code in my API file but I don't understand how to manage below two async calls to execute the function in order can someone help me to resolve the issue or can I use promise to solve the issue.

Thanks in advance for the help.

function getDataFromBK() {
  connection((db) => {

    var comment = "";
    db.collection('comment')
      .find({
        "appNo": appNo
      }, {
        "filename": fileName
      })
      .toArray()
      .then((filelist) => {
        /* response.data = filelist;
         res.json(response);*/

        comment = filelist[0].comment;
        console.log("comment-->" + comment);

        return comment;
      }).catch((err) => {
        console.log("err-->" + err);

        return err;
      })
  });


  filepath = path.join(__dirname, '../../uploads/output/' + req.body.appNo) + '/' + req.body.filename[i];
  fileInfo.push({
    "originalName": req.body.filename[i],
    //"size": req.body.filename.size,
    "b64": new Buffer(fs.readFileSync(filepath)).toString("base64"),
    "comment": comment
  });
}
6
  • What is the question actually? Commented Oct 5, 2018 at 6:45
  • I want to use both calls in one function & the response of the first call I want to use in the second call. Commented Oct 5, 2018 at 6:47
  • 1
    This looks like a NodeJS and MongoDB question to me. Commented Oct 5, 2018 at 6:51
  • yes correct I am using mongo with node Commented Oct 5, 2018 at 6:52
  • Which version of NodeJS are you using? Commented Oct 5, 2018 at 6:53

1 Answer 1

1

Since comment is set inside then, you can't expect it to be available where you're doing fileInfo.push as the find operation is going to be async in nature.

Try restructuring your code like this:

function getDataFromBK() {
  connection((db) => {

    var comment = "";

    db.collection('comment')
      .find({ "appNo": appNo }, { "filename": fileName })
      .toArray()
      .then(filelist => {

        comment = filelist[0].comment;

        filepath = path.join(__dirname, '../../uploads/output/' + req.body.appNo) + '/' + req.body.filename[i];
        fileInfo.push({
          "originalName": req.body.filename[i],
          "b64": new Buffer(fs.readFileSync(filepath)).toString("base64"),
          "comment": comment
        });



      })
      .catch(err => err)
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.