0

Here are the codes to promise that i have written

module.exports['getTemplate'] = (object)=>{
  return new Promise((fullfill,reject)=>{
    var content = cache.get(object['template']);
    if(content == null){
      reader("./templates/"+object['template'],'utf8',function(err,data){
        if(err){
          reject(err);
        } else{
          cache.put(object['template'],data);
          fullfill(data,object['data']);
          1) ~~~~>  console.log(object['data']);
        }
      });
    }else{
      fullfill(content,object['data']);
    }
  });
}

module.exports['render'] = (template,context)=>{
  return new Promise((fullfill,reject)=>{
    2 ~~~~~~> console.log(context);
    try{
      var html = mustache.render(template,context);
      fullfill(html,context);
    }catch(err){
      reject(err);
    }
  });
}

and i am calling them using promise in main app like

helper['parseJson'](item)
    .then(helper['getTemplate'])
    .then(helper['render'])

The problem is that the value is set in first console.log but becomes undefined in second function although the value of template is coming all fine. Can someone please explain to me where am i going wrong ?

georoot
  • 3,557
  • 1
  • 30
  • 59
  • 1
    Promises can be fulfilled with only one argument (the rest is ignored) ... see http://stackoverflow.com/questions/22773920/can-promises-have-multiple-arguments-to-onfulfilled – Marco Gabriel Godoy Lema Jan 20 '17 at 19:16
  • If you want to resolve with more than value from a promise, you have to put the values into an object and then resolve with that object. `resolve()` only takes one argument. – jfriend00 Jan 20 '17 at 19:17
  • @MarcoGabrielGodoyLema thanks a lot. Thats something new for me today :D – georoot Jan 20 '17 at 19:17

1 Answers1

1

Promises can be fulfilled with only one value. You'll need to resolve an object or array if you need multiple values:

module.exports['getTemplate'] = (object)=>{
  return new Promise((fullfill,reject)=>{
    var content = cache.get(object['template']);
    if(content == null){
      reader("./templates/"+object['template'],'utf8',function(err,data){
        if(err){
          reject(err);
        } else{
          cache.put(object['template'],data);

          fullfill({template: data, context: object['data']});
          1) ~~~~>  console.log(object['data']);
        }
      });
    }else{
      fullfill(content,object['data']);
    }
  });
}

module.exports['render'] = (data)=>{
  return new Promise((fullfill,reject)=>{
    2 ~~~~~~> console.log(data.context);
    try{
      var html = mustache.render(data.template,data.context);
      fullfill({html: html, context: data.context});
    }catch(err){
      reject(err);
    }
  });
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

Matt Altepeter
  • 956
  • 1
  • 8
  • 18