在Loopback中实现回调'在保存之前'钩

时间:2017-03-02 11:58:53

标签: javascript node.js strongloop loopback

美好的一天!我是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
 }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您应该在外部函数中实现promise,然后等待外部API调用并使用resolve回调返回响应。

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