Lesson 2: Working with web services CHAPTER 8 377
response.end('{ "result": ' + result + '}');
console.log('Handled addition request for x=' + x + ' : y=' + y);
});
app.post('/subtraction', function (request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
var x = Number(fields.x),
y = Number(fields.y),
result = math.subtraction(x, y);
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{ "result": ' + result + '}');
console.log('Handled subtraction request for x=' + x + ' : y=' + y);
});
});
app.put('/multiply', function (request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
var x = Number(fields.x),
y = Number(fields.y),
result = math.multiplication(x, y);
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{ "result": ' + result + '}');
console.log('Handled multiplication request for x=' + x + ' : y=' + y);
});
});
app.delete('/divide', function (request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
var x = Number(fields.x),
y = Number(fields.y),
result = math.division(x, y);
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{ "result": ' + result + '}');
console.log('Handled division request for x=' + x + ' : y=' + y);
});
});
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
Using jQuery promises
You can see that jQuery simplifies the AJAX calls. All these functions execute the same code
when successful, and you might want to refactor this code to call a common function. You
might also be working with a large application that calls addNumbers from multiple func-
tions, but you want different code to execute on success. There is no code to deal with errors.
You also might want to execute cleanup code regardless of whether the AJAX call is successful
or failed. Most important, you might want to execute another AJAX call after the first AJAX
call is successful. You can use promises to accomplish this.