Wednesday, 31 May 2017

Node: Combining Async/Await with Bluebird

Lately I've been using async/await syntax with NodeJs, and I'm loving it. But occasionally, I want to use some of the functionality of libraries like bluebird. In those cases, I'm having issues with execution order. For example:

// look for template having multiple possible file extensions
async function getTemplateFile(templateDir, stackName) {
  const f = await Promise.any(_.map(['yml', 'json', 'yaml'], async(ext) =>
    await util.fileExists(`${path.join(templateDir, stackName)}.${ext}`)));
  if (f) return f;
  else throw new Error(`Stack template "${stackName}" not found!`);   
}

The above code will always throw the 'not found' exception the first time I run it, but succeed thereafter (something to do with file system data being cached on subsequent executions?).

How can I avoid the seeming race condition here? Should I abandon async/await syntax entirely and just use standard .then / .catch notation if I have to use native bluebird functionality?



via rumdrums

No comments:

Post a Comment