Call an api every time the const name is called

Let’s says I have an api endpoint at http://localhost:3000/api and I would like to parse that api very time a const is called. Kinda like this

const c = require(“centra”)

const getAPI = c(‘localhost:3000/api’).send()

// call the const


For some reason this doesn’t seem to work on my local environment. To read the api I’m using a package called centra with node. Any suggestions?


API requests are asynchronous. That means that if you do this:

const c = require('centra')
const getAPI = c('localhost:3000/api').send();

Then Node will fire off the request, but it will not wait for it to complete and will instead move straight on to logging the value of the getAPI variable, which will be undefined, as the request is still in progress.

One way around this is to use async...await, which will (as the name suggests) cause the runtime to wait for the result of an asynchronous operation.

You see this in the example on the package’s npm page:

const c = require('centra')

;(async () => {
    const res = await c('').send()
    console.log(await res.text())

Notice how the API call is wrapped in an anonymous function that is marked as async and within the function it is awaiting the result of the call.

This is a fairly fundamental (if not rather confusing) concept in JavaScript.

I would recommend that you read this:


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.