Promise
-
giúp mình cách dùng promise đoạn code này với.Nghĩa là cho chạy các lệnh query xong hết mới chạy res.render
var theloai = "",nam = "",tuoi = "",quocgia = "";
var query = db.query("SELECT * FROM theloai", (err,result) => {
if(err) return console.error(err);
console.log(JSON.parse(JSON.stringify(result)));
return theloai = JSON.parse(JSON.stringify(result));
});var query = db.query("SELECT * FROM luatuoi", (err,result) => {
if(err) return console.error(err);
tuoi = JSON.parse(JSON.stringify(result));
});
var query = db.query("SELECT * FROM quocgia", (err,result) => {
if(err) return console.error(err);
return quocgia = JSON.parse(JSON.stringify(result));
});
// res.end()console.log('theloai');
console.log(theloai);
return res.render('addFilm',{theloai:theloai,nam:nam,tuoi:tuoi,quocgia:quocgia});
-
function query(query) { return new Promise((resolve, reject) => { db.query(query, (err,result) => { if(err) reject(err); resolve(JSON.parse(JSON.stringify(result))); }); }) } function render(req, res) { const promiseTheLoai = query("SELECT * FROM theloai"); const promiseLuaTuoi = query("SELECT * FROM luatuoi"); const promiseQuocGia = query("SELECT * FROM quocgia"); Promise.all([promiseTheLoai, promiseLuaTuoi, promiseQuocGia]).then((datas) => { console.log(datas); // => [data the loai, data lua tuoi, data quoc gia] res.render('addFilm',{ theloai: datas[0], tuoi: datas[1], quocgia: datas[2] }); }).catch(err => handleError(err)) }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
-
Wow thank anh nhiều nha :))
-
This post is deleted!
-
Cho mình hỏi nếu mình viết vậy có ổn không nhỉ:
const items=product.getAll();
Promise.all([items]).then((datas) => {
const itemRelated = product.related(datas[0].id); Promise.all([itemRelated]).then((result) => { res.render('watch', { items:datas[0], itemRelated:result[0] }); }) })
Có cách nào khác không nhỉ, mình bắt buộc lấy id để tìm những sản phẩm khác cùng loại, nếu để trên thì hàm nó không hiểu.
-
@Sang-Nhoc Ok bạn. Nhưng nên thêm catch ở cuối Promise đển gửi lỗi cho người dùng hoạc throw đến handle error của express
-
Mình có thắc mắc nếu như vậy sau này có nhiều câu lệnh sql mà bắt buộc lấy id câu lệnh sql trên.
Promise.all() => {
Promise.all() => {
Promise.all() => {}) })
})
Mình cứ viết lồng vậy có ổn không nhỉ, thấy nó không được hay cho lắm, có cách nào giải quyết vấn đề này ko bạn.
-
@Sang-Nhoc Bạn đâu nhất thiết viết lông.
Cú pháp của bạn sai đó. Promise là giúp code viết ngang dòng. Trong then của Promise. Khi return về 1 Promise tiếp hoặc 1 object đều sẽ .then được tiếp kiểu nhưa().then((result) => { return "b"; }).then((res) => { console.log(rest); // res === "b" });
Return 1 giá trị hay 1 Promise đều .then như Promise được hết nhé. Vì Pattern Promise A+ khi vào Promise sẽ là 1 chuỗi Promise liên tục.