2017-03-02 1 views
0

안녕하세요! Node.js와 Loopback을 처음 접했습니다. 아래는 나를 미치게합니다.루프백에서 콜백 구현 '저장하기'후크

"저장하기 전에"에 내 모델 인스턴스에 속성 값을 쓰고 싶습니다. 나는 호출 REST 호출에서 하나 개의 값을 얻을 :

ctx.instance.hash

그럼, 내가하는 REST API를 호출 응답을 얻고, 모델에 값을 작성해야합니다. API 호출에서 값을 가져 오는 것은 작동하지만 다른 함수에서 값을 가져옵니다.

그러나 나는 다음을 수행하기 위해, 원래의 함수의 범위에 다시 값을 얻을 수 없습니다 : 내가 시도

tx.instance.somedata = externalData;

이를 글로벌 VAR 만들기 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 
} 

답변

0

외부 함수에서 약속을 구현 한 다음 외부 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) 
    }) 
} 
+0

정말 고마워요! – Grahnite

0

OK, 나는 연구 할 수 있었던 것과, 나는 위의 실용적인 솔루션을하지 않는 것으로, 길을 내 응용 프로그램의 작동을 변경해야합니다.