Tools: JavaScript ES6
I haven't seen a good succinct answer about the syntax of chaining multiple promises to execute in order. I thought this would be a good nail in the coffin question for all promise newbies out there. :)
My Issue is that I want to call this in a synchronous order getPosts--->getThreads--->initializeComplete()
Here is what I am doing.
userPromise.then(getPostsPromise).then(getThreadsPromise).then(initializeComplete()); - userPromise is Promise obj I returned from another part of the code
- getPostsPromise returns a Promise and makes a fetch to the server for posts
- getThreadsPromise returns a Promise and makes a fetch to the server for threads
- initializeComplete is a callback to tell my program that it is initialized.
Here is an example of one of the promises in the chain:
var getPostsPromise = function(){ //Firebase is just a simple server I'm using var firebasePostsRef = new Firebase("https://myfburl.firebaseio.com/posts"); var postsRef = firebasePostsRef.child(localPlace.key); return new Promise(function(resolve, reject) { //Below is a Firebase listener that is called when data is returned postsRef.once('value', function(snap,prevChild) { var posts = snap.val(); AnotherFile.receiveAllPosts(posts); resolve(posts); }); }); } But initializeComplete() is being called before getPostsPromise and getThreadsPromise have a chance to finish fetching.
Why is that happening and how do I write the promises to execute in order?
initializeComplete()...