Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any issues with returning from a function before a promise has been resolved?

I have a javascript (node.js v12) async function that is used to get a resource. It first makes a call to a cache to check if the resource is cached. If it is, then the cached resource is returned. If it is not, then it gets the resource from the path, puts it in the cache, and then returns the resource. The function to put the resource in the cache is async. However, there is no need to wait for this to complete to return the resource. Will it cause any issues if you return from a function while a promise within the function is not yet resolved? I don't even need to know if the function errored because even if the resource can't be put in the cache, I still want to return the resource. Basic example below:

async function getResource(path) {
  const cachedResource = await getResourceFromCache(path).catch(logError);
  if (cachedResource) {
    return cachedResource;
  } else {
    const resource = await getResourceFromPath(path);
    putResourceInCache(path, resource).catch(logError); // This is an async function but I did not use await
    return resource;
  }
}

app.post('/test', async (req, res) => {
  // Code ...
  const resource = await getResource(path));
  // Code ...
  return res.status(200).send(value);
});
like image 753
Alec Fenichel Avatar asked Jun 20 '20 22:06

Alec Fenichel


1 Answers

If you are not waiting for an asynchronous function to return a value, that's okay and you can still go on with the script.

However, make sure you are handling errors (which you do), so the program will not crash.

like image 191
SomoKRoceS Avatar answered Oct 04 '22 10:10

SomoKRoceS