I'm trying out the gtmetriks api with nodejs. i've an index.js file where i handle incoming requests, then i've a gtmetriks.js file to make requests to the api.
The problem is that i don't know how to configure it to get the data in index.js only after gtmetriks.js has finished the request and got the data.
index.js:
const gtmetriks = require('../gtmetrix/gtmetrix');
router.get('/api/gtmetriks', (req, res) => {
const result = gtmetriks()
console.log(result);
res.send(result);
})
gtmetrriks.js:
const api = async () => {
console.log('starting');
// Run test from London with Google Chrome
const testDetails = {
url: 'http://google.com/',
location: 2,
browser: 3
};
const test = await gtmetrix.test.create(testDetails);
console.log('test: ', test);
const data = await gtmetrix.test.get(test.test_id, 5000);
console.log('data: ', data);
return data
}
module.exports = api;
The result in the browser is {}. I assume that this is the value of 'result' because this is the value it gets when it gets initialised.
What am i supposed to do?
Your api
function is async
and therefore returns a Promise
that you need to await in your route handler :)
Try
router.get('/api/gtmetriks', async (req, res) => {
const result = await gtmetriks()
console.log(result);
res.send(result);
})