How to neatly chain promises in Javascript

Home / Uncategorized / How to neatly chain promises in Javascript

Question:
How can I write this function neater, is returning then resolving it in the timeout callback the best way to do this? I’m asking because I’m new to javascript promises.
getStuff(): Promise {
let self = this;

return new Promise(function(resolve, reject) {
self.getData()
.then(function(resp) {
self.parse(resp);
})
.then(function() {
setTimeout(function() {
resolve();
}, 5000);
});
});
}


Answer:
It seems getData is Promise so you don’t need to construct another one.

However it looks you trying recursive call. Means you will need termination somewhere.
getData(): Promise {
let self = this;

If(some conditions)
Return true or something…..

return new Promise(function(resolve, reject) {
self.getData()
.then(function(resp) {
self.parse(resp);
})
.then(function() {
setTimeout(function() {
resolve();
}, 5000);
});
});
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *