简体   繁体   中英

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);
});

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.

There is nothing wrong with this. You just need to handle any exceptions that might arise. Altenatively, you can use event emitters to do this kind of tasks. Emit an event and have a listener commit resource to the cache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM