0

As you can see below, the array "arr" only works inside the .then() function. how can i prevent this

let arr =[];
l.kategoriler.findAll({where:{server_id: "991656640401113118"}}).then(a =>{
    a.map(b =>{
        arr.push(b.kategori)
    })
    console.log(arr) //right array return
})
console.log(arr) // returns []
  • It's all about the timing of when things run. Asynchronous operations in nodejs, run sometime LATER, but they don't block execution of other code. So, `console.log(arr) // returns []` is running BEFORE the `.then()` handler got called. So, it's just logging the initially empty array. The ONLY place to use your results is INSIDE the `.then()` handler or in some function you call from there. – jfriend00 Jul 11 '22 at 00:03

1 Answers1

1

This is happening because the console.log gets to run before the dbquery which is running asynchronously, finishes. When using .then, whatever you want to do with the values should happen within the callback function of the operation.

A neater way of achieving what you want would be to use async-await. Your code structure would change a bit.

let arr =[];
let a = await l.kategoriler.findAll({where:{server_id: "991656640401113118"}})
    a.forEach(b =>{
        arr.push(b.kategori)
    })
console.log(arr)

It is vital that the function containing this snippet is an async function if not you'd encounter errors.

You could read up on async-await if you need to here: https://javascript.info/async-await

ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
Lord Bee
  • 132
  • 6