M
M
Mazino2019-02-21 14:51:03
JavaScript
Mazino, 2019-02-21 14:51:03

How to output the result of an async function to an external variable?

I am using the mysqljs library, which makes an asynchronous request to the database, and returns the result in a callback function:

var data = [];
connection.query('select * from `users` where `is_enabled` = 1;', (err, response) => {
  if(err) throw err;
  data = response.map(item => item.value);
        console.log(data)//array data
});
console.log(data)//undefined

It’s clear to me why this happens, but despite the mountain of re-read material, I still couldn’t display the data so that I could work with it synchronously, either all the logic should be inside the asynchronous function, or call another one inside it and pass the data there , and thus the result of its work is again not available to the synchronous code, and this can continue indefinitely. Is there a way to store asynchronous data into a variable and work synchronously? Thanks in advance for your help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Okhotnikov, 2019-02-21
@tsepen

This is called callback hell, they did it before, but now you can use async await

I
Interface, 2019-02-21
@Interface

async/await will save you!
You can read here https://habr.com/ru/company/ruvds/blog/326074/, for example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question