0

When i call rest API and return response it show undefined but i console.log this response it return

var request = require("request");

function initialize() {
  // Setting URL and headers for request
  var options = {
    url: 'http://postalpincode.in/api/pincode/400605',
    json: true
  };
  // Return new promise 
  return new Promise(function (resolve, reject) {
    // Do async job
    request.get(options, function (err, resp, body) {
      if (err) {
        reject(err);
      } else {
        resolve(JSON.stringify(body));
      }
    })
  })

}

function main() {
  var initializePromise = initialize();
  initializePromise.then(function (result) {
    return result;
  })
}
console.log('', main())

But when i console log this response it show output correct

var request = require("request");

function initialize() {
  // Setting URL and headers for request
  var options = {
    url: 'http://postalpincode.in/api/pincode/400605',
    json: true
  };
  // Return new promise 
  return new Promise(function (resolve, reject) {
    // Do async job
    request.get(options, function (err, resp, body) {
      if (err) {
        reject(err);
      } else {
        resolve(JSON.stringify(body));
      }
    })
  })

}

function main() {
  var initializePromise = initialize();
  initializePromise.then(function (result) {
    console.log('', result)
  })
}
console.log('', main())

I want When i call rest API and return response it show correct output

rahul5140
  • 140
  • 1
  • 15
  • Use a call back in main or create a promise in main or use async and await. That is asynchronous function. – Shubham May 03 '19 at 09:42
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – 1565986223 May 03 '19 at 10:02

5 Answers5

2

The return inside the thenscope is not returning for the function main, but only for the thenscope of the promise. You need to return the promise like so:

function main() {
  var initializePromise = initialize();
  return initializePromise.then(function (result) {
    return result;
  })
}

main().then((result) => console.log('',result));

you can't make a sync function call an async method and expect to have get its result.

wilovent
  • 1,364
  • 1
  • 12
  • 15
1

use async/await

async function main() {
  var initializePromise = await initialize();
  console.log(initializePromise)
}
narayansharma91
  • 2,273
  • 1
  • 12
  • 20
  • While using a async/await it return `Promise { } {"Message":"Number of Post office(s) found: 1","Status":"Success","PostOffice":[{"Name":"Kalwa","Description":"","BranchType":"Sub Post Office","DeliveryStatus":"Delivery","Taluk":"Thane","Circle":"Thane","District":"Thane","Division":"Thane Central","Region":"Mumbai","State":"Maharashtra","Country":"India"}]}` – rahul5140 May 03 '19 at 09:48
  • print your result using `initializePromise.PostOffice` and see what will print. – narayansharma91 May 03 '19 at 09:52
  • so what ? i think this one is true answer ! – Ömür Alçin May 03 '19 at 09:53
  • async/await is just another tool to handle async behaviour. However, op needs a better understanding of how promises and async works. – mobby May 03 '19 at 09:56
  • While result using `initializePromise.PostOffice` it will print `undefined` – rahul5140 May 03 '19 at 09:56
0

My question is, why are you wrapping in a new Promise something that's already from a return type of Promise?

You could just do:

request.get(endpoint, options).then((response) => console.log(response)).catch((error) => console.log(error));

Let me know what's the output in that case.

Rafael Rocha
  • 508
  • 1
  • 3
  • 16
0

The then resolution of initializePromise method resolves at a later stage when a response is fetched from REST HTTP call i.e. it does not get returned when you call main() method due to the fact it is async. To handle such code, you should either use a callback

function main(completionHandler) {
  var initializePromise = initialize();
  initializePromise.then(function (result) {
    completionHandler(result);
  })
}
main((result) => { console.log(result)})

or a promise

function main() {
    // Return new promise 
    return new Promise(resolve => {
        var initializePromise = initialize();
        initializePromise.then(function (result) {
            resolve(result);
        })
    }
}

main().then(result => console.log(result));
mobby
  • 361
  • 4
  • 8
0
return new Promise(function (resolve, reject) {
    // Do async job
    request.get(options, function (err, resp, body) {
      if (err) {
        reject(err);
      } else {
        try {
          resolve(JSON.stringify(body));
        } catch(e) {
          reject(e);
        }
      }
    })
  })

in main function:

function main() {
  initialize().then((result) => {
    console.log(result);
    return result;
  }).catch((err) => {
     console.log(err);
     return err;
  })
}
Murtaza Hussain
  • 3,851
  • 24
  • 30