0

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((content) => {
        console.log(content);
        //want to render this content
    });

    //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{<pending>}". How do I use the data in content outside the promise.

  • Where is `content` defined? – guest271314 May 11 '17 at 22:29
  • 2
    *"How do I use the data in content outside the promise."* you don't. use it in the callback. – Kevin B May 11 '17 at 22:31
  • @guest271314 I meant data, but I have changed the code to content. Basically I want to send that data returned from the promise to the front-end template. (commented out). – user3315810 May 11 '17 at 22:47
  • @KevinB .. but I want to send that returned data to the front-end template. How I can achieve that? – user3315810 May 11 '17 at 22:49
  • Place `var template = fs.readFileSync("./public/template.ejs", "utf8"); //var rendered = ejs.render(template, {content}); res.send(name);` within body of function passed to `.then((content) => { });` – guest271314 May 11 '17 at 22:50
  • @user3315810 Your send needs to wait for the promise. There's no way around that. – Bergi May 11 '17 at 23:03

0 Answers0