Srinesh Srinesh - 1 year ago 80
Javascript Question

What is the best way to wrap synchronous functions in to a promise

Let's say i have a Synchronous function like

. I want to wrap that in to a
because i want excetions to be handled within
If i wrap like below, i can not an exception in
block. So I have to use
to check the return value, if it's a error or not and then call resolve, reject functions. Are there any other solutions?

var joinPaths = function(path1,path2) {
return new promise(function (resolve, reject) {
resolve(path.join(path1, path2));

Answer Source

It is unclear why you would wrap a synchronous operation in a promise as that just makes it more difficult to use and synchronous operations can already be used within promise chains just fine.

The only two places I've seen it useful to make a promise out of something synchronous are to start a promise chain where subsequent operations will be async or when you are branching and one result of the branch is async promise and the other is synchronous. Then, in that case, you want to just return a promise in both cases so the caller has a consistent async interface no matter which branch is taken.

Other than that, you should generally not make synchronous things async because it just unnecessarily complicates using them.

The simplest way I know of to make it into a promise would be this:

Promise.resolve(path.join(path1, path2)).then(function(path) {
   // use the result here

Per your comments, inside a .then() handler, exceptions are already captured by the promise infrastructure and turned into a rejected promise. So, if you had this:

someAsyncOp().then(function(value) {
   // some other stuff
   // something that causes an exception
   throw new Error("timeout");
   console.log(err);   // will show timeout

Then, that exception is already mapped into a promise rejection for you. Of course, if you want to handle the exception inside of the .then() handler (not turn the promise into a rejection), then you can just use a traditional try/catch around your synchronous operation to catch a local exception (no different than any other synchronous code). But, if you want the promise to reject if there's an exception inside the .then() handler, then that is all done for you automatically (a very nice feature of promises).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download