I have a simple express application which receives a POST request and performs calls to different API's. I want to send out an email when one or more of the API requests return an error. A simplified version of what I am doing is as follows: File app.js
var express = require('express');
var request = require('request');
var email=require('./elasticemail.js');
var numApiRequests=3;
var wasError=false;
var responseToClient;
app.post("/", function(req, res) {
responseToClient=res;
request({/*first request data*/},function (error, response, body){
if (error)
wasError=true;
done()
}
request({/*second request data*/},function (error, response, body){
if (error)
wasError=true;
done()
}
request({/*third request data*/},function (error, response, body){
if (error)
wasError=true;
done()
}
}//app.post
function done(){
isDone++;
if (isDone===numApiRequest){
if (wasError){
email.send('an error occurred')
responseToClient.send('there was an error')
}
else
responseToClient.send('everything was fine')
}
}//done
This works fine as long as there is just one request at a time, but if there is more than one request at a time, the variables "wasError", "responseToClient" are affected by the actions performed for each request. Is there any way so that these variables can be accessed by the done() function but are not accessed by other requests? I know that I could declare such variables inside app.post() and pass them as a parameter to done(), so that they don't need to have global scope, but I am looking for a generic method to limit the scope of a variable to the context of a request.