Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have a synchronous function like path.join(). I want to wrap it into a Promise because I want exceptions to be handled within catch() block. If I wrap it like below, I do not get an exception in the Promise's .catch() block. So I have to use if to check the return value for whether it's an error or not and then call resolve or reject functions. Are there any other solutions?

var joinPaths = function(path1,path2) {
  return new promise(function (resolve, reject) {
    resolve(path.join(path1, path2));
  });
};
like image 688
s1n7ax Avatar asked Apr 24 '16 17:04

s1n7ax


2 Answers

Very quick way is to wrap prepend a function with async keyword. Any async function returns a Promise

const sum = async (a, b) => a + b;

sum(1, 2).then(value => console.log(value))
like image 122
The.Wolfgang.Grimmer Avatar answered Sep 26 '22 05:09

The.Wolfgang.Grimmer


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);
    }
})
like image 41
Thanish Avatar answered Sep 26 '22 05:09

Thanish