저는 NodeJS에서 n00b이므로이 질문은 다소 초보적 일 수 있습니다.NodeJS + MongoJS : 중첩 콜백 문제
논리적으로 관련된 두 개의 모음을 읽으려면 MongoJS를 사용하고 있습니다. 첫 번째 find()은 내가 필요한 정보를 얻으려면 두 번째 찾기()에 전달하는 값을 반환합니다.
몇 가지 전략을 시도했습니다. 마지막으로 (스 니펫 # 1) 내가 내보내는 클래스입니다.
이전에 반환 함수을 가져 와서 원하는 값인 "config [0]"을 반환했습니다.
이 코드에서는 "sapConfig"속성을 "test"라는 단어로 설정했지만이 코드를 실행할 때 "get_config()"를 호출하면 "sapConfig"값이 항상 "null"이됩니다. 메서드 및 - 이상한 - "this.sapConfig = 'test'"에 대한 참조는 "undefined의 속성 'sapConfig'를 설정할 수 없습니다."라는 오류를 생성합니다.
난 그냥 반환 문 간단한 함수로 코드를 한 경우 ((니펫을 # 2) 오류가 발생되지 않았다하지만 반환 값은 항상 CONSOLE.LOG하지만 "정의"입니다) 문이 보여 반환되는 변수의 값이 원하는 값을 갖습니다. 뭐라 구요?
코드 조각 # 1 : 그것은 라인을 실행할 때 나는를 호출 "GET_CONFIG()"오류의 결과를 할 때 반환이, 다시
"use strict";
var mongojs = require('mongojs'); // MongoDB API wrapper
module.exports = function(regKey) {
this.regKey = regKey;
this.sapConfig = null;
this.get_config = function() {
// Read SAP connection information from our MONGO db
var db = mongojs('mongodb://localhost/MIM', ['Configurations','Registrations']);
db.Registrations.find({ key: this.regKey }, function(err1, registration){
console.log('Reg.find()');
console.log(registration[0]);
db.Configurations.find({ type: registration[0].type }, function(err2, config){
console.log('Config.find()');
console.log('config=' + config[0].user);
this.sapConfig = 'test';
});
});
}
this.get_result = function() {
return this.sapConfig;
}
}
, 조각 # 1의 코드 객체 "this.sapConfig = 'test'".
그러나이 오류가 발생하면 "obj.get_result()"를 실행할 수 있으며 초기화 된 값, 즉 null이 반환됩니다. 즉, 같은 코드는 "이것은"
코드 조각 # 2 ") (GET_CONFIG"는 .IN 같은 방법
를 정의되어 있지 않다는 오류를 생성하지 않습니다 다음 문 "반환"사용"use strict";
var mongojs = require('mongojs'); // MongoDB API wrapper
module.exports = function(regKey) {
// Read SAP connection information from our MONGO db
var db = mongojs('mongodb://localhost/MIM', ['Configurations','Registrations']);
db.Registrations.find({ key: regKey }, function(err1, registration){
console.log('Reg.find()');
console.log(registration[0]);
db.Configurations.find({ type: registration[0].type }, function(err2, config){
console.log('Config.find()');
console.log('config=' + config[0].user);
return config[0].user;
});
});
}
반환 값을 받고 검사하면 "정의되지 않음"입니다. 예를 들어, 노드 CL에서 나는 다음과 같은 명령을 실행
var config = require('./config') // The name of the module above
> var k = config('2eac44bc-232d-4667-bd24-18e71879f18c')
undefined <-- this is from MongoJS; it's fine
> Reg.find() <-- debug statement in my function
{ _id: 589e2bf64b0e89f233da8fbb,
key: '2eac44bc-232d-4667-bd24-18e71879f18c',
type: 'TEST' }
Config.find()
config=MST0025
> k <-- this should have the value of "config[0]"
undefined
당신은 쿼리가 성공했음을 볼 수 있지만 "K"의 값이 "정의"입니다. 무슨 일 이니?
내가 어떤 접근 방식을 사용하든 신경 쓰지 않고 그 중 하나만 작동하면됩니다.
미리 감사드립니다.
두 번째 부분에 대한 내 대답은 내 새로운 예제를 참조하십시오 :) 건배. – matt