I am learning ES6 promises, and want to confirm that I'm understanding the syntax. (If this works but there's a better way, I'd love to know that, too!)
Suppose I'm writing a function which returns a promise. (Let's say because I want to wrap a sequence of async().then().then().then()'s in a function.)
Question 1: Am I correct thinking that I need a function, wrapped in a then(), wrapped in a executor function, wrapped in a promise constructor, wrapped in the original function, like the below?
function iReturnAPromise() {
//do some stuff here
return new Promise(function(resolve, reject) {
doAnAsyncThing()
.then(...)
.then(...)
.then(function(results) {
//resolve with another promise or reject with an error based on results
});
});
}
That amount of nesting seems crazy, and worse than the "callback hell/pyramid of doom" that promises are designed to fix. Am I overcomplicating (probably because I'm misunderstanding some part of promises) or is that really the syntax?
Question 2: Let's assume that really is the syntax. Are the following two snippets equivalent? Is one more idiomatic than the other?
a) Do a bunch of stuff before the return statement, and stick only the async thing inside the promise executor, like so:
function iReturnAPromise() {
//do stuff here
//do more stuff
//do even more stuff
return new Promise(function(resolve, reject) {
doAnAsyncThing()
.then(...)
.then(...)
.then(...);
});
}
b) Wrap everything in the promise executor, like so:
function iReturnAPromise() {
return new Promise(function(resolve, reject) {
//do stuff here
//do more stuff
//do even more stuff
doAnAsyncThing()
.then(...)
.then(...)
.then(...);
});
}