1

I want to return an object out of a callback. When I run the below code, the log of the body object looks as expected. It appears to be the correct JSON object containing the response I want from the server: name, email, website, etc.

But the result object appears to contain information about the request itself instead of the response object.

How do I return the body object so that I can access it from the result variable?

const request = require('request'); // npm i request -s

module.exports = async config => {
  ...

  const result = await request.get( url, options,
    ( error, response, body, ) => {
      console.log( 'body', body, ); // I want the other log to look like this log.
      return body;
    }
  );

  console.log( 'result', result, ); // I want this log to look like the above log.
  // In other words, I want the below line to be the name, email, website JSON object
  // contained in the body
  return result;
}

This is what I want from result.

console.log( 'body', body, );
body {
  "name": "foo",
  "email": "foo@example.com",
  "website": "www.example.com",
  ...
}

This is what I actually get from result.

console.log( 'result', result, );
result Request {
  _events: [Object: null prototype] {
    error: [Function: bound ],
    complete: [Function: bound ],
    pipe: [Function]
  },
  _eventsCount: 3,
  _maxListeners: undefined,
  uri: Url {
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'api.example.com',
    port: 443,
    hostname: 'api.example.com',
    hash: null,
  },
  callback: [Function],
  method: 'GET',
  readable: true,
  writable: true,
  explicitMethod: true,
  _qs: Querystring {
    request: [Circular],
    lib: { formats: [Object], parse: [Function], stringify: [Function] },
    useQuerystring: undefined,
    parseOptions: {},
    stringifyOptions: {}
  },
  _auth: Auth {
    request: [Circular],
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • it's because you have the return statement inside the `request.get` callback. Because you named the constant request variable as the `request.get` method, it will always be an instance of that method unless you change it to a `let` or `var` and declare it as something else inside the request callback. – ezra Jan 15 '20 at 19:56
  • They're are different kind of objects, please read this: https://www.linkedin.com/pulse/whats-difference-between-javascript-object-json-kishorkumar-bachhav – Triby Jan 15 '20 at 20:04
  • @E2017: What would be an example of how I would implement your answer explicitly in code? Could you please provide an example? – Let Me Tink About It Jan 15 '20 at 20:25
  • From the docs it looks like requiring `[request-promise-native](https://www.npmjs.com/package/request#promises--asyncawait) ` may be what you're looking for. – traktor Jan 15 '20 at 22:01
  • [npm package request-promise-native](https://www.npmjs.com/package/request-promise-native) – traktor Jan 15 '20 at 22:09

0 Answers0