Background
I
am trying to learn promises, and I have a promise chain I want to improve
on.
Problem
While
learning how to chain promises, I fail to see why anyone would rather return a promise
instead of returning it's value.
Take the
following example, which uses promise
chaining:
let myObj =
new MyClass();
myObj.getInfo()
.then(result =>
writeOutput(FILE_NAME, result))
.then(console.log(FILE_NAME + "
complete"))
.catch(error =>
console.error(error));
class
MyClass{
getInfo() {
return new
Promise(function(fulfil, reject) {
fulfill("I like bananas");
});
}
Here I
have to chain 2 times. But if I were to directly return the result from the method
getInfo()
instead of returning a Promise I could potentially do
something like the following:
let
myObj = new MyClass();
let str =
myObj.getInfo();
writeOutput(FILE_NAME, str)
.then(console.log(FILE_NAME + " complete"))
.catch(error =>
console.error(error));
Questions
So
as you can see I am a little
confused.
- Given that
getInfo()
is in fact async, is it possible to achieve a similar
code to the one in my second code sample? - If it were
possible, would it be a good idea? How would you do
it?
No comments:
Post a Comment