Shehzad Lokhandwalla Shehzad Lokhandwalla - 5 months ago 7
JSON Question

How to pass information to the view after function completion when using NodeJS Request?

I'm writing code that would fetch some JSON data and pass it on to a new view with the given data.
The view is called /newbook2 and I want to pass information such as book name, author name and so on to the view from a JSON file called through an API.

var s_book_name;
var s_author_name;
var s_isbn13_id;
var s_publisher_name;
var s_category_id;
var error="";

router.post('/searchbook', function(req, res){

var isbn=req.body.isbn;
var url="http://isbndb.com/api/v2/json/63JEP95R/book/"+isbn;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
if(body.data[0].title!=null)
s_book_name=body.data[0].title;
if(body.data[0].author_data[0]!=null)
s_author_name=body.data[0].author_data[0].name;
if(body.data[0].isbn13!=null)
s_isbn13_id=body.data[0].isbn13;
if(body.data[0].publisher_name!=null)
s_publisher_name=body.data[0].publisher_name;
if(body.data[0].subject_ids[0]!=null)
s_category_id=body.data[0].subject_ids[0];
}
else error="Book not found. Please enter the information manually."
});
res.redirect('/newbook2');

});


However, the information insn't yet loaded in my view. It seems like a common problem with asynchronous calls. However, I'm new to nodejs and would appreciate any help on how to fix it.

router.get('/newbook2', function(req, res){
res.render('newbook2', {title: 'Add New Book',s_book: s_book_name, s_author: s_author_name, s_isbn13: s_isbn13_id ,s_publisher: s_publisher_name , s_category: s_category_id});
});

Answer

You need to use promises for this. Here is some sample code for you to refer to make the POST call.

router.post('/newBook', function(req, res, next) {
    console.log('Please add your here to get the data from server');
    Obj.then(function() {
        res.send('You got the success response from the server');
    });
});

res.send('Your Book has been successfully added.'); will only execute after you get the success response from the server. Please go through the concept of promises for more detail.

Comments