1
\$\begingroup\$

app.js

var employees = require('../models/employees');
employees.read(req.params.id, function(body) {
 console.log(body.firstName);
});

models/employees

var request = require('request');
var employees = {
 read: function(id, callback) {
 request
 .get('http://api.mysite.com/employees/' + id, function(error, response, body) {
 body = JSON.parse(body);
 return callback(body);
 })
 },
};
module.exports = employees;

This works (returns the employee name correctly), but I'm not sure if this is the correct (async) way of getting data from an API and displaying it.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 29, 2016 at 7:24
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You didn't implement any error handling. Before doing something with the api response body, you should check if an error occured. Also the callback function of your read method should use the error first pattern. Here is a very short explanation: http://www.codingdefined.com/2015/10/what-are-error-first-callbacks-in-nodejs.html

Further, JSON.parse can throw an error if your api doesn't respond with a valid json string. So you might want to handle this error, too. Just add a try-catch block.

answered Dec 16, 2016 at 20:50
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.