【问题标题】:Getting no value in second function of promise [duplicate]在承诺的第二个功能中没有价值[重复]
【发布时间】:2017-06-05 20:35:12
【问题描述】:

这是我承诺的代码

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);
    }
  });
}

我在主应用程序中使用promise 给他们打电话,比如

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

问题是该值是在第一个 console.log 中设置的,但在第二个函数中变为 undefined 尽管模板的值一切正常。有人可以向我解释我哪里出错了吗?

【问题讨论】:

  • Promises 可以只用一个参数来实现(其余的被忽略)...见stackoverflow.com/questions/22773920/…
  • 如果你想从一个promise中解析出更多的值,你必须把值放入一个对象中,然后用那个对象解析。 resolve() 只接受一个参数。
  • @MarcoGabrielGodoyLema 非常感谢。今天对我来说是新事物:D

标签: node.js promise


【解决方案1】:

Promise 只能通过一个值来实现。如果需要多个值,则需要解析对象或数组:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 2021-05-19
    • 2021-06-29
    • 1970-01-01
    • 2021-02-18
    • 2017-12-21
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多