Answer the question
In order to leave comments, you need to log in
Help me make promises?
There is a modular code built on classes. There is a main class that requaries all other modules and creates objects based on these classes. The chain of calls is large. Did everything on await\async. But in one piece of code everything skips, await does not work. There are two functions that are almost next to each other:
await isNew();
/*
Code
*/
await prepeare();
async isNew() {
let res = false;
let deDB = this.deDB;
await new Promise((resolve, reject) => {
deDB.each("SELECT id, dt FROM meta", function(err, row) {
console.log(err);
if (err)
res = true;
//console.log("User id : "+row.id, row.dt);
});
});
console.log('res is ' + res);
return res;
}
async prepare() {
let sSql = new Array();
let deDB = this.deDB;
await new Promise((resolve, reject) => {
deDB.serialize(async function() {
deDB.run("CREATE TABLE meta (id INT, dt TEXT)");
deDB.run("CREATE TABLE lorem (info TEXT)");
console.log('i am in prepare');
let stmt = deDB.prepare("INSERT INTO lorem VALUES (?)");
for (let i = 0; i < 10; i++) {
await stmt.run("Ipsum " + i);
}
stmt.finalize();
console.log('Метка 1');
});
});
console.log('Метка 2');
await deDB.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
}
)
console.log('Метка 3');
return true;
}
Answer the question
In order to leave comments, you need to log in
Here you have created a promise , but you need to resolve it from the inside sometime! Inside the Promise, summon the
Promise - a time bomb. Which is not immediately, but should either jerk or blow away . just waits until the promise explodes with some result. new Promise((resolve, reject)...
resolve(result)
result = await my_promise;
function isNew() {
// !!! Обязательно нужно вызвать один из callback
return new Promise((resolve, reject) => {
deDB.each("SELECT id, dt FROM meta", function(err, row) {
if (err) {
// этот вызовит отрицательный результат, который можно обраюатывать в цепочке c catch
reject(err)
} else {
// этот вызовит положительный результат, который можно обраюатывать в цепочке c then
resolve(row)
}
});
});
}
try {
const result = await isNew()
console.log(result)
} catch (e) {
console.log('Ошибка:', e)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question