0

I want make a function for calling API. If I execute "apifunc", the function calls the api. When the API execution is complete, the results are saved in "body". Now I want the function to return the "body". But it does not. The console did print out the "body". So the api worked. The problem here is return. How do I fix this problem.

exports.apifunc=function(a,b){
var request = require('request'); 
request.post(`https://abc.co.kr/api/${address}`,
{ json: {A:`${a}`, B: `${b}`} },
function (error, response2, body) {
  if (!error && response2.statusCode == 200) {
    console.log(body);
    return body;
  }
 });
}
Sihoon Kim
  • 1,481
  • 2
  • 13
  • 32
  • 3
    Possible duplicate of [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) – Sebastian Speitel Aug 13 '18 at 11:01

1 Answers1

1

Welcome to asynchronous programming, man!

You are using callback style, that means that all further actions you should perform inside request callback and so on deeper and deeper if you are doing async stuff with the result of initial request.

My solid advice is to use request-promise library and async/await flow. Look:

const request = require('request-promise');

exports.apifunc= async (a,b) => {
  const body = await request.post(
    `https://abc.co.kr/api/${address}`,
    { json: { A:`${a}`, B: `${b}`} }
  );

  return body;
}

Don't forget two things here. Errors handling is desired (try/catch) and that async function returns Promise. So, the outer funtion, that uses api function should either be async in order to await body there, or expect Promise and continue Promise chain by .then