Let's say i have a Synchronous function like path.join()
. I want to wrap that in to a Promise
because i want excetions to be handled within catch()
block.
If i wrap like below, i can not an exception in Promise
's .catch()
block. So I have to use if
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));
});
};
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. Or, this could also occur with different implementations of a common API, one implementation which is synchronous and the other asynchronous. The API would be designed with an asynchronous interface and the synchronous implementation would probably wrap itself in a promise to fulfill the asynchronous contract of the common API.
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");
}).catch(function(err){
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).
Not sure if it's the best way but it works. I came to StackOverflow to check if there's a better way.
new Promise((resolve, reject) => {
try {
resolve(path.join());
} catch (err) {
reject(err);
}
})