简体   繁体   中英

While call rest api in Javascript (NodeJS) and return response Undefined

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

The return inside the then scope is not returning for the function main , but only for the then scope 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.

use async/await

async function main() {
  var initializePromise = await initialize();
  console.log(initializePromise)
}

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.

The then resolution of initializePromise method resolves at a later stage when a response is fetched from REST HTTP call ie 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));
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;
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM