What is the best way to wrap synchronous functions in promise

Say I have a synchronous function like path.join() . I want to wrap this in Promise because I want excetions to be processed in a catch() block. If I wrap as shown below, I cannot exclude in the block Promise .catch() . Therefore, I should use if to check the return value if it is an error or not, and then call a solution, reject the function. Are there any other solutions?

 var joinPaths = function(path1,path2) { return new promise(function (resolve, reject) { resolve(path.join(path1, path2)); }); }; 
+6
source share
1 answer

It is unclear why you are completing a synchronous operation in a promise, as this simply complicates its use, and synchronous operations can already be used in entire chains of promises.

Only two places that I saw useful to promise from something synchronous are to start a chain of promises where subsequent operations will be asynchronous or when you fork, and one branch result is asynchronous and the other is synchronous. Then in this case, you just want to return the promise in both cases so that the caller has a serial asynchronous interface no matter which branch is busy.

Other than this, you usually should not do async synchronous things, because it just unnecessarily complicates their use.

The easiest way I know to do this in a promise would be as follows:

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

In your comments inside the .then() handler, exceptions are already caught by the promise infrastructure and turned into a rejected promise. So, if you have 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 this exception is already displayed in the promise for you. Of course, if you want to handle the exception inside the .then() handler (not turn the promise into a failure), then you can simply use the traditional try / catch around your synchronous operation to catch the local exception (not just any other synchronous code). But if you want the promise to be rejected, if there is an exception in the .then() handler, then all this is done for you automatically (a very nice function promises).

+7
source

Source: https://habr.com/ru/post/1247820/


All Articles