Your problem is that the code is async. Therefore, what's happening is something like this:
You set body.entity.type = "coke"
You make an async call
You set body.entity.type = "pepsi"
You make another async call
The interpreter is idle (no more javascript to run)
therefore it can execute networking code.
Javascript makes first network request
with body.entity.type = "pepsi"
Javascript makes second network request
with body.entity.type = "pepsi"
Network requests complete (may be in order may be not, depending
on which arrives first) and calls the callback.
So both console.log will have "pepsi" because objects are references and you're passing the same object to both requests.
It IS possible to make this work with plain objects:
var body1 = {
entity: {
type: "coke"
}
};
var body2 = {
entity: {
type: "pepsi"
}
};
product.list(body1)
.then(console.log);
product.list(body2)
.then(console.log);
If you want to make the code more reusable, either use a constructor:
function Body (type) {
this.entity = {type: type};
}
product.list(new Body('pepsi'))
.then(console.log);
product.list(new Body('coke'))
.then(console.log);
Or use a function that returns object literals:
function makeBody (type) {
return {entity: {type: type}};
}
product.list(makeBody('pepsi'))
.then(console.log);
product.list(makeBody('coke'))
.then(console.log);
The difference between a global reference to a single object and an object created inside a function is that the former is just one object shared between two events waiting to happen in the future, the later are two separate objects passed to two separate events.