user1037355
user1037355

Reputation:

Custom node sync function

Node offers lots of core functions in 2 flavours, sync and async.

Sync functions like fs.readFileSync are very helpful for when starting an app, eg in the npm package dotenv.

Is it possible to write a custom Sync function that does not require the async and await keywords thus bypassing the promise and callback hell?

Upvotes: 2

Views: 1689

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

Is it possible to write a custom Sync function that does not require the async and await keywords thus bypassing the promise and callback hell?

Yes. Just have that function only use the Sync versions of any API functions it calls.

If the function has to use an async API function or module, then no, you can't (readily) make your own Sync version of it (nor do you want to). You could fire off a separate child process to do that async work and wait for it synchronously (execSync, spawnSync)... (I don't recall the specifics, but there is at least one npm module that does that for some reason...)


...but they cannot be used in class constructs or in the more typical server.js starting point of an app...

Yes they can, in both cases. Here's an example:

function somethingAsync() {
  return new Promise(resolve => {
    setTimeout(resolve, 400, Math.floor(Math.random() * 10));
  });
}

// Using async/await in a class:
class Example {
  async doSomething() {
    let a = await somethingAsync();
    return a * 2;
  }
}

// Using async/await in a top-level script:
(async () => {
  try {
    const ex = new Example();
    console.log("Waiting...");
    const v = await ex.doSomething();
    console.log(v);
  } catch (e) {
    console.error("Error: ", e);
  }
})();

Note that it's important to use the try/catch around the body of that async function (or use .catch on its return value), to avoid getting an unhandled rejection error if the function's promise (remember, async functions return promises) is rejected.

Upvotes: 1

Related Questions