E
E
ettaluni2021-01-22 11:08:21
JavaScript
ettaluni, 2021-01-22 11:08:21

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();

In the first case, when there was no promise in both of these functions, the code for working with the database was skipped, everything went to “Label 2” and exited. The base was 0kb.

In the second case, I added a promise to the section with queries to the database in the prepare function. The code stops at "Label 1".

After that, I also added a promise to the isNew() function. And now the Prepare function is not executed at all. Why, the isNew() function itself is not fully executed. The program ends its work.

At this point, I realized that I had ceased to understand something ... Someone please explain how to make the program work normally, without these jumpers, but sequentially as in normal languages. Do not suggest changing the language, this is the last project on JS, I will not return to it again. Thank you!
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

2 answer(s)
S
Sergey Sokolov, 2021-01-22
@sergiks

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;

A
Andrey Pastukhov, 2021-01-22
@tyllo

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 question

Ask a Question

731 491 924 answers to any question