How to assign the callback variable "cursor.toArray(err, doc)" to an external variable?

Asked

Viewed 102 times

1

var result = [];
var user = db.collection('user');
var cursor = user.find();
cursor.toArray(function (err, doc) {
    result = doc;
});
console.log(result); // console -> []
  • Puts a console log. inside the callback and see if it has any value

  • Yes, when I put the console.log inside the callback, the value is assigned perfectly. However, outside the callback, it doesn’t work.

2 answers

2


The problem is just Synchronization

You are experiencing this error because the find() method is asynchronous, in which case you have a Promisse that may not have been solved before the console.log(result),

var result = [];
var user = db.collection('user');
var cursor = user.find(); 

//Aqui você tem uma Promisse
cursor.toArray(function (err, doc) {
    result = doc;
});
console.log(result);//Caso a Promisse não tenha sido executada ainda, result ainda é um Array vazio

An interesting way to perform could be so depending on your version of Node:

async function getResults() {
    db.collection('user').find()
}

var results = await getResults();
results = results.toArray();

Dai your code looks like a synchronous code. The key here is the async / await command that awaits the results of the promise. More info, link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_assincronas

  • It is... really the problem is the same synchronization, as you mentioned. I did some tests with async, await, according to your tips, but it gave some errors here, but I believe it is related to npm packages or something related to Node. One error was solved and another appeared, so I thought I better adapt my classes using everything within callbacks even to resolve this issue. But I will continue researching on this subject of async and await. I found it interesting. Thank you so much for answering my question. Thanks!!!

  • @Leandrosciola as I said depends on the version of Node. Blz mano, da uma lida em promise then it’s quiet

0

Stayed like this:

function find(query, callback) {

    db.collection('user').find(query).toArray(function (err, doc) {
        callback(err, doc);
    });
}

find({name: 'Leandro'}, function (err, doc) {

    let result = [];
    result['user'] = doc;
    console.log(result['user']); // console -> [ { name: 'Leandro', _id: 5a1d624e79a88f09fb805a35 } ]
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.