1

I have a set of if-else conditions which calls a few functions and attribute properties to usr before redirecting this data to an external application.

if(funcA()) {
  usr.a = funcA();
} 
if(funcB()) {
  funcB(user,context,function (error, ticket) {
      usr.ticket = ticket;
  });
}
redirect(usr);

funcB has two async API calls (using axios) and the script always trickles down to redirect before funcB returns a value.

function funcB(user, context, callback) {
    let ticket = '';
    const axios = require('axios@0.19.2');
    const options = {method: 'POST', url: 'xxxx', data: '{xxxx}'};
    axios(options).then(res => {
        const access_token = res.data.access_token;
        const options = {method: 'POST', url: 'xxx', data: `{xxxx}` };
        axios(options).then(res => {
            ticket = res.data.ticket;
            callback(null, ticket);
        }).catch(err);
    }).catch(err);
}

I have tried using callback and async await but unsure how to wait for user.Ticket to be populated before redirect(usr) is called.

fireball.1
  • 1,413
  • 2
  • 17
  • 42

1 Answers1

0

Making funcB return a promise should do the trick.

function funcB(user, context) {
  return new Promise((resolve, reject) => {
    const options = { method: "POST", url: "xxxx", data: "{xxxx}" };
    axios(options)
      .then((res) => {
        const access_token = res.data.access_token;
        const options = { method: "POST", url: "xxx", data: `{xxxx}` };
        axios(options)
          .then((res) => {
            resolve(res.data.ticket);
          })
          .catch(reject);
      })
      .catch(reject);
  });
}

Then use async await

if(funcB()) {
  usr.ticket = await funcB(user,contex)
}

redirect(usr);

Edit: im assuming that the context where the if condition is running is already an async function if not you can do this

(async ()=>{
  if(funcB()) {
    usr.ticket = await funcB(user,contex)
  }
  
  redirect(usr);
})()