【问题标题】:Implement Callbacks in Loopback 'Before Save' hook在 Loopback 'Before Save' 挂钩中实现回调
【发布时间】:2017-03-28 12:31:43
【问题描述】:

美好的一天!我对 Node.js 和 Loopback 很陌生。下面让我发疯。

我想在“保存前”将属性值写入我的模型实例。我从调用 REST 调用中得到一个值:

ctx.instance.hash

然后,我需要调用 REST API,获取响应,并将值写入模型。从 API 调用中获取值有效,但我从另一个函数中获取值。

但我无法将值恢复到原始函数的范围内,以执行以下操作:

tx.instance.somedata = externalData;

我尝试过: 1. 将其设为全局变量,但在原始调用函数中,该值仅保持“undef”。 2. 对值进行“返回”

两者都无济于事 - 值仍然“未定义”

我在想变量永远不会被填充,我需要使用回调,但我不确定在这种情况下如何实现回调函数。

任何指点或帮助将不胜感激,谢谢!

module.exports = function(Blockanchor) {

  Blockanchor.observe('before save', function GetHash(ctx, next) {
    if (ctx.instance) {
      //console.log('ctx.instance', ctx.instance)
      var theHash = ctx.instance.hash; //NB - This variable is required for the external API call to get the relevant data

      //Run below functions to call an external API
      //Invoke function
      ExternalFunction(theHash);
      //See comment in external function, I do not know how to get that external variable here, to do the following:
      ctx.instance.somedata = externalData;

    } 
    next();
  }); //Blockanchor.observe

}//module.exports = function(Blockanchor)

Function ExternalFunction(theHash){
  //I successfully get the data from the external API call into the var "externalData"
  var externalData = 'Foo'
  //THIS IS MY PROBLEM, how do I get this value of variable  "externalData" back into the code block above where I called the external function, as I wish to add it to a field before the save occurs
 }

【问题讨论】:

    标签: javascript node.js strongloop loopback


    【解决方案1】:

    您应该在您的外部函数中实现一个承诺,然后等待外部 API 调用并使用解析回调返回响应。

    module.exports = function(Blockanchor) {
    
      Blockanchor.observe('before save', function GetHash(ctx, next) {
        if (ctx.instance) {
          //console.log('ctx.instance', ctx.instance)
          var theHash = ctx.instance.hash; //NB - This variable is required for the external API call to get the relevant data
    
          //Run below functions to call an external API
          //Invoke function
          ExternalFunction(theHash).then(function(externalData){
            ctx.instance.somedata = externalData;
    
            next();
          })
        } else {
            next();
        }
      }); //Blockanchor.observe
    
    }//module.exports = function(Blockanchor)
    
    function ExternalFunction(theHash){
        return new Promise(function(resolve, reject){
            var externalData = 'Foo'
            resolve(externalData)
        })
     }
    

    【讨论】:

      【解决方案2】:

      好的,根据我的研究,我需要改变我的应用程序的工作方式,因为上面似乎没有一个实际的解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-28
        • 2010-12-29
        • 2022-10-09
        • 2020-12-05
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 1970-01-01
        相关资源
        最近更新 更多