[Fixed] Express resolving route before API call completes

Issue

Ok, full disclosure I am a hobby coder so I understand there to be gaps in my knowledge. However I’ve tried all sorts of solutions for this and have been unable to get a working answer.

DESIRED RESULT

I make a call to my Express server, it fetches data from an external API and renders once the data has been retrieved.

PROBLEM

I cannot seem to make Express wait no matter how I lay out the async/await pattern. Currently my code is as follows:

Express.js

app.get('/getInventory', async (req, res) => {
  try {
    let inventory = await api.getInventory(req.query.id)
    console.log(inventory)
    res.json(inventory)
  }
  catch(err) {
    console.log(err)
  }
})

My api.js is currently as such:

exports.getInventory = async function(id){
    let data = await manager.getInventoryContents(id, 570, 2, true, (err, inventory) => {
        if (err) {
            console.log(err)
            Promise.reject(err)
        } 
        else {
            console.log('Success')
            Promise.resolve(inventory)
        }
    })
    return data
}

In case you’re wondering I have the console.log() actions just to try and see when something is happening.

WHAT I AM GETTING SO FAR

With just about every variation I am getting the Express.js inventory as undefined (similarly no data being sent to the client), however I AM receiving a Success message (or even the inventory itself) from api.js.

I am guessing the right syntax is obvious once I complete it but I cannot seem to get it to function properly. What am I missing?

Solution

Try this:

exports.getInventory = async function(id){
   return new Promise((resolve, reject) => {
      manager.getInventoryContents(id, 570, 2, true, (err, inventory) => {
         if (err) {
            console.log(err);
            reject(err);
         } 
         else {
            console.log('Success');
            resolve(inventory);
         }
      }
   }
}

Leave a Reply

(*) Required, Your email will not be published