Thursday, 11 May 2017

How to handle asynchronous chained promises?

I have program which extracts the data from the movie database. I have written a function which extracts the data form the api using jQuery, which is as follows.

var get_details = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'json';
        xhr.onload = function() {
            var status = xhr.status;
            if (status == 200) {
                resolve(this.responseText);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
};

I have a route in my main file which uses the above function. I am passing the promised returned data using chained promises. The code is as follows.

app.get("/actor", function(req, res){ 
    var name = req.query.actor;
    var id_url = `http://api.tmdb.org/3/search/person?api_key=${api_key}&query=${name}`;
    var promise = data.get_details(id_url).then((data) => {
        var json = JSON.parse(data);
        var id = json.results[0].id;
        return id;
    }).then((id) => {
        var movie_url = `http://api.themoviedb.org/3/discover/movie?api_key=${api_key}&with_cast=${id}`;
        var x = data.get_details(movie_url);
        console.log(x);
        return x;
    }).then((data) => {
        console.log(data);
    });

    //console.log(main);
    var template = fs.readFileSync("./public/template.ejs", "utf8");
    //var rendered = ejs.render(template, {content});
    res.send(name);
});

I am successfully able to extract the data, and the content variable in logging out correct output. I wanna use this content outside this promise, so that I can use it in this line of code.

//var rendered = ejs.render(template, {content});

I am currently getting the error "promise{}". How do I use the data in content outside the promise.



via user3315810

No comments:

Post a Comment