5

I'm using Typescript with nodejs.I have callback function and i'm getting data as a object in body when i console. I want to pass data in data key of ctx.body. Can i push that object in other variable and then pass to ctx.body?

router.post('/api/send_otp', async (ctx: Koa.Context, next: () => Promise<any>) => {
        var phone = ctx.request.body.phone;

        if (!phone) {
            ctx.body = {
                message: "Please enter phone number",
            };
        } else {

    var options = {
        url: '',
        method: 'POST',
        auth: {
            'user': '',
            'pass': ''
        },
    };

    const callback = function(error, response, body) {
        if (response) {
            console.log(body); // Getting data here
        }else{
            console.log('error',error);
        }
    };

    request(options,callback);

    ctx.body = {
        data: body,   //I want data here
    }
});
Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Lux Jan 19 '20 at 13:59
  • @Lux I tried some solution but not working for me. –  Jan 19 '20 at 14:02
  • You need to convert `request` to a promise style function. Then you can `await` it. (you should be inside an `async` function when you're using koa. For older koa versions `yield` it) – Lux Jan 19 '20 at 14:05
  • @Lux Can your edit my question? So i can understand easily how to do it. –  Jan 19 '20 at 14:08
  • could you post the wrapping `koa` code? – Lux Jan 19 '20 at 14:10
  • @Lux check now i've posted it. –  Jan 19 '20 at 14:16

1 Answers1

0

You can convert your callback style to promise and do it like this

const options = {
  "url": "",
  "method": "POST",
  "auth": {
    "user": "",
    "pass": ""
  }
};

function makeCall() {
  return Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (response) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

makeCall
  .then(body => {
    ctx.body = {
      "data": body   // I want data here
    };
  });


Please note that request is not maintained any more so better to use some modern packages like got and axios.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35