sách gpt4 ăn đã đi

javascript - 模型对象构造函数中的 node-mysql 查询

In lại Tác giả: Walker 123 更新时间:2023-11-30 23:10:12 27 4
mua khóa gpt4 giày nike

我是 javascript 的初学者。我尝试编写一个用于 Express 和 node-mysql 的模型。它定义了类 Place。
当我创建一个对象实例时:var p = new Place(10); 它应该初始化对象并填充变量。但是初始化数据存储在数据库中,查询是异步的,所以我认为该对象是首先创建的,我不知道从数据库返回的数据会发生什么以及如何正确初始化对象实例变量。

var db = app.db; // app is set as GLOBAL

// constructor
var Place = function(place_id) {
this.getPlaceById.call(place_id, function(err, result){
if (err) throw err;

this.id = result.id;
this.title = result.title;
this.city = result.city;
this.address = result.address;
});
}

Place.prototype.getPlaceById = function (place_id, callback) {
db.query(
'call getPlaceById(?);', /* call stored procedure */
[ place_id ],
function(err, results, fields) {
if(err) {
callback(err);
} khác {
callback(null, results[0][0]);
}
}
);
}

module.exports = Place;

结果我得到了一个奇怪的错误:

function(place_id) {
...
} has no method 'replace'
at Object.SqlString.escape (.../node_modules/mysql/lib/protocol/SqlString.js:40:13)
at .../node_modules/mysql/lib/protocol/SqlString.js:72:22
at String.replace (native)

如果我留下空的构造函数并调用:

p.getPlaceById(10, function(err,r) {
console.log(r)
});

它可以正常工作并返回正确的数据。

câu trả lời hay nhất

我找到了解决方案:

var Place = function(place_id, fn) {
var self = this;

Place.prototype.getPlaceById.call(this, place_id, function(err, result){
if (err) {
fn.call(self, err)
}
khác {
self.id = result.id;
self.title = result.title;
self.city = result.city;
self.address = result.address;

fn.call(self);
}
});
}

然后创建一个对象实例:

var p = new Place(place_id,function(err,result){
if (err)
console.log(err)
khác
console.log(p);
});

关于javascript - 模型对象构造函数中的 node-mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20139976/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress