0

I have a problem when it comes to create an object in javascript inside a promise chain. For some reason it gets all messed up and my attributtes are not showing correctly:

var historyManager = new HistoryManager();
var examManager = new ExamManager();
var recipeManager = new RecipeManager();
var historiaObj = {
    obs : "",
    freR : "",
    exams : [],
    meds : [],
    content : ""
};
var allHistory = Object.create(historiaObj);
return historyManager.refresh(history).then(function (historyRefreshed) {
    history = historyRefreshed;
    allHistory.obs = historyRefreshed.get("obs");
    return examManager.getByHistory(historyRefreshed);
}).then(function (examenFisico) {
    allHistory.freR = examenFisico.get("freR");
    return recipeManager.getByHistory(history)
}).then(function (recipe) {
    allHistory.content = recipe.get("content");
    return recipeManager.getMedsByRecipe(recipe);
}).then(function (meds) {
    for(var i = 0 ; i < meds.length ; i++){
        allHistory.meds.push(meds[i].get("name"))
    }
}).then(function () {
    return allHistory;
});

For some reason when I try to check if the meds where added correctly, they are under _proto_ but not in the main object. How can I fix this, or what is it that I'm doing wrong.

Thanks in advance.

ocespedes
  • 1,233
  • 4
  • 14
  • 27
  • You may also want to have a look at [How do I access previous promise results in a .then() chain?](http://stackoverflow.com/q/28250680/1048572). Especially that global `history` variable seems to be problematic – Bergi Aug 10 '15 at 12:41

1 Answers1

0

Your issue does not appear to be promise related. The behavior you're seeing is how Object.create works:

Object.create(proto);

Object.create is used when you want to create a new object to instantiate with new. It doesn't look like you need to use Object.create here. Just assign the plain object to allHistory.

var allHistory = {
    obs : "",
    freR : "",
    exams : [],
    meds : [],
    content : ""
};
Andy Ray
  • 30,372
  • 14
  • 101
  • 138
  • It does indeed solve my problem, but this is just a part of my real problem, will this have the same behavior if I want to create and array of allHistory objects? I mean in that case I will have more than one object to create. – ocespedes Aug 10 '15 at 05:17
  • You could do something like `for( var x = 0; x < 10; x++ ) { histories.push({ objs: "" ... }); }` which would create a new object for every array element. Or you could use underscore or a similar library which provide a `clone` function to clone basic vanilla objects. – Andy Ray Aug 10 '15 at 05:48