Answer the question
In order to leave comments, you need to log in
NodeJS async\await in ES6 classes not working?
Good day! I'm trying to get my code to work the way I wrote it.
There is a chain of calls:
module1.init()->module1.getProjectStatus()->module2.isNew(); Naturally, everything is through await \ async
In order for the code to work at least a little as I wrote, I have to insert async \ await wrapper functions.
The problem is that it skips the isNew() function, for example, as a result, the variable remains not initialized, it executes it at the end, but I need it at the beginning.
I used to write on Prototype -> function and in general there were no problems with asynchrony, I set await and it will wait. Govonokod but worked. And then I decided to keep up with the times, I implemented everything in the classes, the code is sweet in constructors, but it works as it wants.
Maybe these sugar constructions in the form of constructor - class intervene implementations of await?
Here is an example code:
let pState = false;
await (async () => {
pState = await this.getProjectStatus();
console.log('pState is getProjectStatus' + pState);
return;
})();
console.log('pState is ' + pState);
if (pState == 'new')
await this.prepare();
class SuperClass {
constructor (settings) {
if (!this.isCorrectSettings())
console.log('Settings is incorect');
let defaultSettings = {
MAX_UPDATE_TIME: 5, //hours
PRG_WORK_DIR: __dirname,
PROJECT_DIR: __dirname,
};
this.settings = Object.assign(defaultSettings, settings);
//T-200
}
async init() {
await this.initPaths();
await this.initModules();
await this.initVars();
isNew() {
let res = false;
let deDB = this.deDB;
let fd = deDB.run("SELECT id, dt FROM meta", function(err) {
if (err)
res = true;
console.trace('Step1');
});
console.trace('Step2 ' + res);
return res;
}
Step2 false
Step3 false
Step4 contunue
Step5 contunue
End of test - O213k4
getArrayRows - Error ads
getArrayRows - Error matrix
getArrayRows - Error meta
Step1
Answer the question
In order to leave comments, you need to log in
If you want to call your functions after the database request callback is triggered, then you need to either:
1) Specify these functions already inside the callback (it will call these functions itself)
2) Promise the database call function so that you can apply await (or then, whoever is comfortable):
const runBdQuery = query => new Promise((resolve, reject) => {
deDB.run(query, function(err) {
if (err)
reject(err);
res = true;
resolve(res) // тут все что угодно
console.log('Step1');
});
})
const makeQuery = async () => {
const query = "SELECT id, dt FROM meta";
await runBdQuery(query);
await step1();
----------
await step6();
}
makeQuery();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question