2012-07-13 2 views
1

아래 코드는 return_info가 설정을 가져 오지 않는 것을 제외하고는 모두 작동합니다. 요청 함수에 의해 호출되는 콜백 내에서 부모 return_info 변수에 액세스 할 수 있습니까?호출 된 함수의 콜백에서 함수 변수에 액세스

module.exports = { 
    fetch_template_by_id : function(id) { 
    var request = require('request'); 
    var return_info = {}; //TO BE MODIFIED 
    request('http://localhost:5000/templates/v1/template/' + id, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
     console.log("Success - Error = " + error + " | Response = " + response + " | Body = " + body); 
     return_info.body = body;     // Should Modify the top 
     return_info.json = JSON.parse(body);  // Should Modify the top 
     return_info.success = true;    // Should Modify the top 
     } else { 
     console.error("There was an error requesting template ID=" + id) 
     return_info.error = error;    // Should Modify the top 
     return_info.response = response;   // Should Modify the top 
     return_info.success = false;    // Should Modify the top 
     } 
    }); 
    return return_info; 
    } 
} 

편집 : 추가 참조를 위해이 코드를 호출합니다.

app.get('/form', function (req, res) { 
var template_helper = require('../services/template-helper'); 
var template = template_helper.fetch_template_by_id("BirthRecord"); 
console.log(template); 
if (template.success === true) { 
    res.render('form', {"template": template.json }); 
} else { 
    res.render('index'); 
} 
}); 

답변

0

요청이 비동기 적이므로 return_info을 반환 한 후에 실행됩니다. 그래서, 당신은

module.exports = { 
    fetch_template_by_id : function(id, cb) { 
    var request = require('request'); 
    var return_info = {}; //TO BE MODIFIED 
    request('http://localhost:5000/templates/v1/template/' + id, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
     console.log("Success - Error = " + error + " | Response = " + response + " | Body = " + body); 
     return_info.body = body;     // Should Modify the top 
     return_info.json = JSON.parse(body);  // Should Modify the top 
     return_info.success = true;    // Should Modify the top 
     } else { 
     console.error("There was an error requesting template ID=" + id) 
     return_info.error = error;    // Should Modify the top 
     return_info.response = response;   // Should Modify the top 
     return_info.success = false;    // Should Modify the top 
     } 
     cb(return_info); 
    }); 
    } 
} 

fetch_template_by_id('awesome', function (info) { 
    console.log(info); 
}); 

편집 아래 표와 같은 함수에 대한 콜백을 제공해야 -

당신은 콜백 방법을 함께 생각해야 할 상황에 맞는 사용하면 Node.js를 작업을 시작하려면 , 아래는 어떻게해야하는지에 대한 예입니다.

app.get('/form', function (req, res) { 
    var template_helper = require('../services/template-helper'); 
    template_helper.fetch_template_by_id("BirthRecord", function (template) { 
    console.log(template); 
    if (template.success === true) { 
     res.render('form', {"template": template.json }); 
    } else { 
     res.render('index'); 
    } 
    }); 
}); 
+0

이 작업은 가능하지만 가능한 한 제품의 흐름을 깨뜨릴 필요가 없습니다. node.js를 처음 사용하기 때문에, 내가 할 수있는 일을 모릅니다. 이 코드를 호출하여 더 많은 컨텍스트를 얻을 수 있습니다. 당신의 솔루션은 여전히 ​​도움이 될 수 있습니다, 나는 단지 그것에 대해 충분히 노드를 알지 못합니다. –

+0

수정했습니다. 확인해주세요. 비동기 적으로 nodejs를 사용하기 전에 콜백을 사용하여 코딩하는 방법에 대해 읽어야합니다. –

+0

그래서 저는 여러분이 위에있는 코드와 거의 동일한 코드를 작성했습니다. 그리고 완벽하게 작동했습니다. 당신의 도움은 저를 올바른 사고 방식으로 데려갔습니다. 제 사고 과정을 확인해 주셔서 감사합니다. 감사. –

관련 문제