美好的一天!我对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
}
非常感谢卡洛斯! – Grahnite