简体   繁体   中英

Sequencing a series of functions with promises in Ember js

I wasn't sure how to title this question.

What I am looking to do is grab a large array of movies, filter out only those that have reviews, then sort the reviews by date desc, then trim the list to grab only the latest 11 before setting the first entry to be featured and returning to the model then. With these numerous calls though, I notice some data being jumbled out of order and I believe it's due to all the calls running simultaneously. How can I use promises to structure this to wait for the previous step to complete before proceeding?

getLatestReviews(num) {
    const movieList = this.getMovies();
    const reviewList = movieList.filterBy('review');
    const indexList = this.sortReviewsByDate(reviewList);
    const latestList = this.getSetAmountOfMovies(num, reviewList);
    return this.setFirstReviewToFeatured(latestList);
},


sortReviewsByDate(arr, dir) {
    dir = dir || 'desc';

    return arr.sort(function(a,b) {
        if (dir === 'desc') { 
            return a.review.date < b.review.date;
        } else {
            return a.review.date > b.review.date;
        }
    });
},
getSetAmountOfMovies(num, arr) {
    const movieList = arr ? null : this.getMovies();
    const trimmedList = arr ? arr.slice(0, num) : movieList.slice(0, num);        
    return trimmedList;
},
setFirstReviewToFeatured(arr) {
    arr[0].isFeatured = true;
    return arr;
},

What I'm experience is once I exceed 10 reviews the ordering starts getting out of whack and I believe it's due to the functions not running in a sequence. But I'm not sure how to use promises to ensure one step is complete before running the next.

You should use promise chain to avoid asynchronous problems :

getLatestReviews(num) {
    return this.getMovies().then(function(movieList) {
       return movieList.filterBy('review');
    }).then(function(reviewList) {
       return //...
    });
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM