JavaScript로 약속을 지키려고합니다. 약속이 무엇인지 아는 것처럼 느껴집니다. 그러나, 나는 그들을 사용하는 방법을 이해하지 않습니다. 학습을 위해 Node.js에서 데이터베이스를 쿼리하기로 결정했습니다. 내 코드에는 test.js.라는 JavaScript 파일 하나가 있습니다. Test.js은 다음과 같습니다JavaScript 약속 설정
Test.js
'use strict';
module.exports = function (app) {
var customerService = require('customer.js')(app);
var getCustomerTest = function() {
customerService.getCustomer(1).then(
function (customer) { console.log(customer); },
function (error) { console.log(error); }
);
};
};
Customer.js
'use strict';
module.exports = function(app) {
var _ = require('lodash');
var db = require('db');
return {
getCustomer: function(customerID) {
try {
console.log('querying the database...');
var database = db.connect(CONNECTION_STRING);
database.query('select * from customers where [ID]="' + customerID + '", function(error, result, response) {
if (error) {
// trigger promise error
} else {
// This throws an exception because displayMessage can't be found.
this.displayMessage('Success');
// trigger promise success
}
});
} catch (ex) {
// trigger promise error
}
},
displayMessage: function(message) {
console.log(new Date() + ' - ' + message);
}
};
};
내가 설정에 getCustomer의 약속을하려고 사투를 벌인거야. 특히 데이터베이스 호출에 대한 호출이 비동기 적으로 발생하기 때문에 특히 그렇습니다. customerService.getCustomer에 대한 제 호출이 올바른 접근이라고 생각합니다. 그러나 getCustomer 내부에는 두 가지 문제가 있습니다.
- 약속을 어떻게 설정합니까?
- 데이터베이스 쿼리가 완료된 후 왜 displayMessage를 호출 할 수 없습니까? 어떻게해야합니까?
자바 스크립트 위즈!
봐 - https://github.com/kriskowal/q 또한, "비동기"이없는 약속뿐만 asyncronous 콜백 - HTTPS : //github.com/caolan/async. 그들은 모두 좋은 문서를 가지고 있으며이 문제를 해결하기 위해 필요한 것입니다. – Dylan