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;
  }
 });
}
1

1 Answer 1

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

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.