建立JavaScript承诺
我正试着用JavaScript来理解承诺。我觉得我知道什么是承诺。然而,我不知道如何使用它们。为了学习,我决定从Node.js查询数据库。在我的代码中,我有一个名为test.js的JavaScript文件。Test.js如下所示: Test.js建立JavaScript承诺,javascript,node.js,Javascript,Node.js,我正试着用JavaScript来理解承诺。我觉得我知道什么是承诺。然而,我不知道如何使用它们。为了学习,我决定从Node.js查询数据库。在我的代码中,我有一个名为test.js的JavaScript文件。Test.js如下所示: Test.js 'use strict'; module.exports = function (app) { var customerService = require('customer.js')(app); var getCustomerTest =
'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); }
);
};
};
'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);
}
};
};
Customer.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); }
);
};
};
'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,我就有两个问题:
此
未引用包含getCustomer
和displayMessage
的对象。这是因为您处于回调函数中,并且上下文已更改
您需要保存对正确上下文的引用,并使用该引用访问displayMessage
getCustomer: function(customerID) {
//saving the context
var that = this;
try {
...
database.query('select * from customers where [ID]="' + customerID + '", function(error, result, response) {
...
// Now use it here to call displayMessage
that.displayMessage('Success');
...
}
});
} catch (ex) {
...
}
},
“我如何设定/回报我的承诺?”
您将需要一个promise库(除非您计划创建自己的库)。为此,我将展示
有几种方法可以做到这一点,但我将展示延迟的用法
基本过程是: