A
A
Alexander Petrov2018-08-16 09:29:24
Node.js
Alexander Petrov, 2018-08-16 09:29:24

How to deal with callbacks in nodejs?

Guys save please please!!!! I am writing an application in electronjs. Accordingly, there is nodejs. The task is very simple, but because of the callbacks I can’t solve it in any way and I don’t understand what to do in this situation at all. This is my first nodejs project, so don't throw rags if I'm asking very simple things.
The task is this:
1) Create a variable
2) Get the value from the cookie and put it in this variable.
3) If the required cookie does not exist, then we get the value from the database
4) We enter the obtained value into a variable and write it to the cookie.
I wrote this code:
PS To work with the database I use sequelize and SQLite
PSS I understand that this code is not working. I've just put the code in the order I see it should run, imagining that it's running synchronously.

var active_account=false; //Создаем переменную с изначальным значением false;
    
session.defaultSession.cookies.get({url: 'http://localhost',name: 'active_account'}, (error, cookie) => {
  cookie=cookie[0];
  active_account=cookie.value; //Получаем значение куки и заносим в переменную
});

if(active_account==false){ //Если значение осталось false (то есть значение не занесли), то начинаем получать значение из бд.
  Account.findOne().then(function(account){ //Обращаемся к БД и берем первое значение
    active_account=account.email; //Заносим значение в переменую
    
    session.defaultSession.cookies.set({url: 'http://localhost', name: 'active_account', value: active_account}, (error) => {}) //Заносим значение в куки
  });
}

console.log(active_account); //PROFIT

I understand that functions can be nested inside each other. But there are not direct dependencies that do not allow it to be done just like that. In addition, all the rest of my code that goes below should use the active_account variable, and then it turns out that all the code also needs to be inserted into a separate callback?
I also tried to use this plugin: https://github.com/ybogdanov/node-sync
But sequelize refuses to make requests at all if I insert somewhere after the sync function. Can you advise how to properly connect some special. plugins and how to make them friends with sequelize?
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Patient322, 2018-08-16
@Mirkom63

async function yourModule () {
...
  const account = await Account.findOne();
  active_account=account.email;
  session.defaultSession.cookies.set({url: 'http://localhost', name: 'active_account', value: active_account}, (error) => {})
...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question