Assuming I have three asynchronous functions to be chained together, func1 --> func2 --> func3, it seems there are two ways to do it.
Option 1: promisify the first function, func1p = Promise.promisify(func1)
, leave the other two alone, and then create a chain like this:
func1p
.then(func2)
.then(func3)
.catch(err)
Option 2: promisify all three functions, func1p = Promise.promisify(func1)
, func2p = Promise.promisify(func2)
, func3p = Promise.promisify(func3)
and then create a chain like this:
func1p
.then(func2p)
.then(func3p)
.catch(err)
According to MDN Web Docs, the then
function (always) returns a new promise. So it seems to me it's not necessary to promisify func2 and func3 because they would have already been 'promisified' by the then
function of the func1p. In other words, option 1 should be enough.
I've tested with both options and both seemed to work and gave the same result to me. My concern, however, is if there's any difference in performance, overhead etc. between the two and if so, which one is better.
My questions:
- Is it a good practice to always promisify all functions and so I should use option 2 instead, or it's the other way around?
- If option 1 is preferred, is it still true if func2 and func3 are to be created from the beginning?
EDIT: Here are my code (I used Express JS and request-promise)
EDIT2:
When I asked this question I assumed my functions are asynchronous and the question is about what I should do with them. I didn't expect it to turn into a discussion about whether my functions are actual asynchronous or not. Imho they may or may not be but there is always the possibility that they will be asynchronous the next time and when I'm not sure, I'd rather assume that they are to be safe. So just to be clear, I edited my code to indicate that func1
, func2
, func3
are indeed asynchronous in this context.
function func1 (filePath1) {
fs.readFile(filePath1, (err, data1) => {
if (err) throw err;
console.log(data1);
});
}
function func2 (filePath2) {
fs.readFile(filePath2, (err, data2) => {
if (err) throw err;
console.log(data2);
});
}
function func3 (filePath3) {
fs.readFile(filePath3, (err, data3) => {
if (err) throw err;
console.log(data3);
});
}