2016-12-20 2 views
0

백엔드 호출을 수행하고 이름 배열을 가져 오는 함수가 있습니다. 이 기능은 다음과 같습니다.NodeJS의 콜백 함수에서 값 받기

module.exports.getTxnList = function(index, callback) { 
    ....some operations 
    ..... 
    .... 
    callback(null, response); 
}; 

나는이 함수를 호출하여이 목록을 얻고 자하는 또 하나의 기능을 가지고 있습니다. 두 기능은 동일한 파일에 있습니다.

다른 기능은 다음과 같습니다.

module.exports.getTxnAvailability = function(index, lid, callback) { 
    ... 
    ... 
    ... 
}; 

나는 많은 것을 시도했지만 전 함수에서 데이터를 얻지 못했습니다.

이것은 내가 시도한 것입니다.

var that = this; 
that.getTxnList(index, function(response){ 
    // Here you have access to your variable 
    console.log("List: " + response); 
}) 

그리고이

var txnList=this.getTxnList(index); 

어떤 도움을 이해할 수있을 것이다.

var txnList = this.getTxnList(index); 

은 다음과 같이 수행합니다 :

+0

질문에 '시도'중 몇 개를 추가하십시오. – Shaharyar

+0

필요한 데이터는 무엇입니까? – azad

+0

@Shaharyar 게시물을 업데이트했습니다. –

답변

1

처럼 두 번째 함수의 첫 번째 함수를 호출 할 수 있어야합니다 때문에 비동기 행동 nodejs

//name the function for local use 
var getTxnList = module.exports.getTxnList = function (index, callback) { 
    ... } 

module.exports.getTxnAvailability = function(index, lid, callback) { 

    getTxnList(index, function(err, response){ 
     //here you have access to your variable 
     //rest of your logic will be written here 

     var txnList = response; 
    }); 
}; 

Reference: to understand how async code works

Reference: to understand what is callback hell and how to solve it

+0

데이터를 가져 오지 못합니다. –

+0

'this'는 문제를 일으키는 것 같아요, 나는'this'를 제거하고 귀하의 함수에 이름을 추가했습니다. 또한 콜백 함수에 2 개의 매개 변수를 전달해야하므로 첫 번째 매개 변수로 'null'을 전달하고 두 번째 데이터를 전달합니다. – Shaharyar

+0

이 필요했습니다. 그렇지 않으면 함수를 인식 할 수 없습니다. 하지만 지금은 일하고 있습니다. 도와 주셔서 감사합니다. 많은 시간을 절약했습니다 :) –

-1

당신은 불행하게도이 작업을 수행 할 수

module.exports.getTxnAvailability = function(index, lid, callback) { 
    module.exports.getTxnList(index, function(err, data) { 
    console.log(data); 
    }); 
}; 
+0

데이터를 가져 오지 못함 –

관련 문제