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?