1

I am trying to create an integration for two websites using API's of both websites.

I created a rest API where both the software can send post and get request and my API will resolve it.

when software 1 makes a post request to my application at "/send_tests", my application needs to get the post request and send it to the 2nd software and return the data that I get from 2nd software to 1st software What I am trying to do is, when I receive a post request at "/send_tests", I am then trying to read the req and then make a post request from my application to another application, and then when I receive the response from the post request I am trying to save it in a global variable and then responding back to the first post request that I got at "/send_tests". But when I try to save the response and try to access it later in the code, I am getting undefined for that variable

//My function to return the data 

async function postData (first_name,last_name, email, URL, token) {

  var data = {

      
      "assessmentStatusWebHook": "http://localhost:3000/api/hook",
      "notifyAssessmentAvailableUsingEmail": 1,
      "firstName": first_name,
      "lastName": last_name,
      "email": email
  }
  axios.post(url, data, {headers: {'Accept': 'application/json'}})
  .then((res) => {
      console.log(`Status: ${res.status}`);
      return  res.data.assessmentId
  }).catch((err) => {
      console.error(err);
  });
    
}; 

//My router to res.send the assessmentId that I get from postData
router.post("/send_tests",  [
check('partner_test_id').exists(),
check('first_name').exists().isString(),
check('last_name').exists().isString(),
check('resume_url').optional(),
check('phone_number').optional().isString(),
check('email').exists().isEmail().normalizeEmail(),
check('url').exists().isString()], async (req, res) => {
  

    let partner_test_id = req.body.partner_test_id;
    let first_name = req.body.first_name;
    let last_name = req.body.last_name;
    let resume_url = req.body.resume_url;
    let phone_number = req.body.phone_number;
    let email = req.body.email;
    let url = req.body.url;
    
    // Send response
    const errors = validationResult(req);
    var assessmentId
    (async () => {
      try {
      //I am trying to save the response from this post 
        assessmentId = await postData(first_name,last_name, email,jobTitle1)
       
      }catch (err){
        console.log ('Errorrrrrrr' + err)
      }
    })();
  
 

     
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }
  console.log("In the function for assessmentID " + assessmentId)
    
res.send({
        //I am trying to access the response from the previos post request "assessmentId"
            "partner_interview_id":assessmentid
          
      });
  
}); ```

I need to save the assessmentID and send it in the res.send as a response. Please Help

khan Safi
  • 23
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Amadan Jul 08 '21 at 04:12
  • var assessmentId (async () => { try { //I am trying to save the response from this post assessmentId = await postData(first_name,last_name, email,jobTitle1) }catch (err){ console.log ('Errorrrrrrr' + err) } })(); res.send({ //I am trying to access the response from the previos post request "assessmentId" "partner_interview_id":assessmentid }); I want to save the response and send it in the res.send. But I am receiving undefined for assessment ID – khan Safi Jul 08 '21 at 21:53
  • Have you read the linked article? There is no way to do it the way you are doing it. Any values received by asynchronous calls have to be used in a callback, in a promise consequence, after an await inside an async function, or in code triggered by one of those. – Amadan Jul 09 '21 at 01:00

1 Answers1

0

You can use async/await as axios returns the promise. You can do something like this:

async getData() {
    const res = await  axios.post(url, data, {headers: {'Accept': 'application/json'}});
    return await res.json();
}
async function getPostedData (first_name,last_name, email, URL, token) {

  var data = {

      
      "assessmentStatusWebHook": "http://localhost:3000/api/hook",
      "notifyAssessmentAvailableUsingEmail": 1,
      "firstName": first_name,
      "lastName": last_name,
      "email": email
  } 
  const results = await getData(); // use the results
   return results;
}; 

//My router to res.send the response 
router.post("/send_tests",  [
....
....

You can check here for more details about axios with async/await.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Sorry, the function name getPostedData is kinda misleading. What I am trying to do is, when I receive a post request at "/send_tests", I am then trying to read the req and then make a post request from my application to another application, and then when I receive the response from the post request, I am then responding back to the first post request that I got. var assessmentId (async () => { try { assessmentId = await getPostedBehavioralData()}catch (err){console.log (err)} })() res.send({ "partner_interview_id":assessmentid });}); – khan Safi Jul 08 '21 at 13:22
  • What is your question? You asked about how to get reponse from axios to the other parts. The answer is not helping you to achieve it if not what do you want to achieve ? – Apoorva Chikara Jul 08 '21 at 13:26
  • I am still getting undefiend for "assessmentId" when I am trying to use outside this IIFE function (async () => { try { assessmentId = await getPostedBehavioralData(first_name,last_name, email,jobTitle1) }catch (err){ console.log ('Errorrrrrrr' + err) } })(); Please take a look at my router.post function – khan Safi Jul 08 '21 at 13:39
  • are you returning the values form `getPostedData` method? This `getPostedBehavioralData ` and `getPostedData` are these both diff methods? You might be using two diff methods and you haven't included `getPostedBehavioralData` in the question. Add `getPostedBehavioralData` function how are you defining it? – Apoorva Chikara Jul 08 '21 at 13:42
  • I edited my original question, postData is the function where I make the post request – khan Safi Jul 08 '21 at 13:47
  • I have updated the answer, it should now return the values. If it throws an error let me know. – Apoorva Chikara Jul 08 '21 at 13:50
  • router.post("/send_tests", async (req, res) => { var assessmentId (async () => { try { //I am trying to save the response from this post assessmentId = await getPostedData(first_name,last_name, email,jobTitle1) }catch (err){ console.log ('Error' + err) } })(); res.send({ //I am trying to access the response from the previos post request "assessmentId" "partner_interview_id":assessmentid }); But when I do this, I don't get the assessment in the response – khan Safi Jul 08 '21 at 19:17
  • Are you returning data from `getPostedData`? If you won't it will never get there. – Apoorva Chikara Jul 09 '21 at 10:01