U
U
ura2rist2020-03-05 13:20:03
Node.js
ura2rist, 2020-03-05 13:20:03

How to return a variable from a function when using findOne?

var menus = [
  {
    id: 1,
    name: 'Список пользователей',
    Parent_ID: 0,
    url: '/list-user'
  },
  {
    id: 2,
    name: 'Добавить пользователя',
    Parent_ID: 0,
    url: '/add-user'
  },
  {
    id: 3,
    name: 'Заявка на редактирование сайта',
    Parent_ID: 0,
    url: '/report-site'
  }
]

let q = filterMenu(menus,request.session.login);
console.log(q);
function filterMenu(menus,login){
    const user = ['Заявка на редактирование сайта'];
    var men = [];
    models.user.user.findOne({where: {login: login}})
    .then(us=>{
        if(us.privilege == 1){
            men = menus.filter(n => user.includes(n.name));
        }else{
            men =  menus;
        }
    })
}

It is necessary to return the men variable already filled, I tried it through setTimeout and a promise - it displays undefine

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Shohruh Shaimardonov, 2020-03-05
@joeberetta

Make filterMenu asynchronous (async filterMenu) and assign models.user.user.findOne to a variable using await. The variable will contain the result of the query

A
Alexander Cheremkhin, 2020-03-05
@Che603000

findOnereturns a promise

function filterMenu(menus,login){
    const user = ['Заявка на редактирование сайта'];
    var men = [];
    return models.user.user.findOne({where: {login: login}})
    .then(us=>{
        if(us.privilege === 1){  // строгое сравнение ===
            return menus.filter(n => user.includes(n.name));
        }else{
            return  menus;
        }
    })
}
...
let q;

filterMenu(menus,request.session.login);
  .then(result=> q==result)

and further. The code is not complete, but I assume that whereit is superfluous
models.user.user.findOne({login: login})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question