I have a case where I need to return a promise in a Node program. There are two ways I can think of doing so, and I was curious if there was an objective, actually superior method of doing so out of the two (or another way I'm missing).
Method 1 - return a base promise without any resolution/rejection:
function getDataFromFile() {
return new Promise((resolve, reject) => {
//resolve if file read, reject if not
});
}
function useDataToDoSomething() {
getDataFromFile().then(data => {
console.log(data);
}).catch(err => {
console.log(err);
}));
}
function useDataToDoAnotherThing() {
getDataFromFile().then(data => {
processData(data);
}).catch(err => {
console.log(err);
});
}
Method 2 - return a promise with resolution/rejection already defined:
function getDataFromFile() {
return new Promise((resolve, reject) => {
//resolve if file read, reject if not
}).then(data => {
return data;
}).catch(err => {
console.log(err);
return null;
});
}
function useDataForSomething() {
console.log(getDataFromFile());
}
function useDataForAnotherThing() {
processData(getDataFromFile());
}
It seems like the first method is a lot more code-heavy and prone to things like copy and paste errors, but it also seems to allow for a lot more flexibility. The second method, on the other hand, seems a lot cleaner but allows less customization and may abstract a lot more from the user.
I guess the sum of what I'm asking - is it better to implement promises that have set resolutions/rejections, even if that may be hidden from the end user, or is it better to just return a base promise and let the user/each individual function define how they want that promise to resolve or be rejected?
via josephmbustamante
No comments:
Post a Comment