1

I'm creating a business dashboard, and need to fetch data from different APIs.

I'm using Glitch.com to build, and requireing the request module for fetching data. Here's the Glitch link to the project: https://glitch.com/edit/#!/achieved-icebreaker?path=server.js:2:0

When I use request inside server.js, it works fine - but when I wrap it in a function as a precursor to separating it into a separate module, I just cannot get it working!

Ideally, I want getCopper() to return a number.

I've trawled through a lot of Stack Overflow posts, help resources, etc.

Initially I was just getting:

Promise { <pending> }

Then I got to the point where console.log(response.headers['x-pw-total'] inside request outputted the desired result, but couldn't pass that to the function in a return.

Now I've got to the point where doing console.log(getCopper()) returns the promise object:

Promise {
  Request {
  domain: null,
  _events: 
   { error: [Function: bound ],
     complete: [Function: bound ],
     pipe: [Function] },
  _eventsCount: 3,
  _maxListeners: undefined,
  method: 'POST',
  headers: (etc etc)

Here's my code right now:

async function getCopper() {
  return request({
    url: "https://api.prosperworks.com/developer_api/v1/companies/search",
    method: "POST",
    headers: {
      'X-PW-AccessToken': process.env.COPPER_KEY,
      'X-PW-Application': 'developer_api',
      'X-PW-UserEmail': process.env.COPPER_EMAIL,
      'Content-Type': 'application/json'
    },
    mode: "no-cors",
    body: JSON.stringify({
      'sort_by': 'name',
      'minimum_interaction_date': moment().subtract(90, 'days').unix(),
      'maximum_interaction_date': moment().unix()
    })
  }, function(error, response, body) {
    return response.headers['x-pw-total'];
  });
}

console.log(getCopper());

How can I get getCopper() to output 768?

Promises make my head hurt


Edit:

I did read through How do I return the response from an asynchronous call? (the question this has been marked as a duplicate of), and couldn't make head nor tail of it.

The code uses try/catch, they're using new Promise and superagent library instead of request.

Undoubtedly it's useful, but I cannot decipher what parts of the answer are useful and relevant, and which parts are irrelevant.

What specifically do I need to do to get my code to work?

Anonymous
  • 193
  • 1
  • 9
  • If `getCopper()` returns a promise, you want `getCopper().then(data => console.log(data))`. This is explained in the **ES2015+: Promises with then()** section of the accepted answer – Phil Sep 04 '19 at 00:32
  • In your question, what is `request`? It doesn't appear to be [request](https://www.npmjs.com/package/request) as that does not return a promise. Is it one of the promise-based implementations listed here ~ https://www.npmjs.com/package/request#promises--asyncawait – Phil Sep 04 '19 at 00:38
  • @Phil thanks for your reply... I am indeed using [request](https://www.npmjs.com/package/request), by `require('request')`. Would this change the answer to the question, or would the answer remain the same even after my incorrect terminology is fixed up? Sorry, noob here! – Anonymous Sep 04 '19 at 00:52
  • @Phil with `getCopper().then(function(response) { console.log(response); })`, it's returning a `Request` object!? See https://glitch.com/edit/#!/achieved-icebreaker?path=server.js:53:2 – Anonymous Sep 04 '19 at 01:00
  • Ah, I missed that `getCopper` is `async`, that's why it returns a promise. Try using one of the promise-based `request` implementations I mentioned earlier. – Phil Sep 04 '19 at 01:01
  • @Phil `return rp` instead of `return request` works great for getting the body of the request. One question though - in `getCopper().then(data => console.log(data))`, is it possible to get the request headers? `getCopper().then(function(error, response, body) { console.log(response.headers) });` comes up with `UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'headers' of undefined`. – Anonymous Sep 04 '19 at 01:07
  • I added another link to the list at the top of your question that shows how to get the response headers – Phil Sep 04 '19 at 01:11
  • Excellent, @Phil - you're the best! I wish I had an un-duplicate question for you to post and answer, *and* enough rep to vote that answer up – Anonymous Sep 04 '19 at 01:23
  • Oh you. You might be interested in [node-fetch](https://www.npmjs.com/package/node-fetch) which is natively promise based and less verbose that `request` (in my opinion). It also means you get used to using the same code both in Node and in the browser. – Phil Sep 04 '19 at 01:26
  • Thanks for that, on my to-do list! Working like a charm now, thanks for all your help – Anonymous Sep 04 '19 at 01:55

0 Answers0