9
9
9karamba2019-02-06 17:54:14
JavaScript
9karamba, 2019-02-06 17:54:14

How to write data from asynchronous function?

For example, there is such a function

function getFiles(directoryPath, arrFiles, callback) {
    fs.readdir(directoryPath, (err, files) => {
        if (err) console.log(err);
        ... //здесь добавляю в массив файлы
        callback(arrFiles);
    });
});

And here I want to get the data, but it outputs undefined
var file;
getFiles("./",[], function(result){
    file = result;
    return file;
});

How to write data to a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Laud, 2019-02-06
@9karamba

Since two answers cannot be added, this answer will have two parts.
Most likely you are doing something like this:

var file;
getFiles("./",[], function(result){
    file = result;
    return file;
});
console.log(file);

If yes, then this is a common mistake for those who are starting to deal with asynchrony.
If you do this, then this is what will happen :
1. A variable has been declared
2. "Create a request to receive files. When they are received, call the callback" (very roughly)
getFiles("./",[], function(result){
    file = result;
    return file;
});

3. Output file (empty)
4. Files received, callback is called. Return doesn't get anywhere from here.
file = result;
return file;

Option 1:
getFiles("./",[], function(result){
    var file = result;
    // Дальше работаем с file здесь
});

Option 2:
function getFiles(directoryPath) {
    return new Promise((resolve, reject) => {
    	fs.readdir(directoryPath, (err, files) => {
         let arrFiles = [];
         // ... Добавляете в arrFiles нужную информацию
               if (err) {
          	console.log(err);
          	reject(err);
          }
          resolve(arrFiles);
      });
    })
};

// где-то выше
async function someFunction() { // Функция, где находится var file и остальное
  // ...

  try {
    var file = await getFiles("./"); // Здесь await заставит ваш код "ждать", пока из Promise в getFiles не будет вызван resolve
    console.log(file);
  } catch (e) {
    // Сделать что-то с ошибкой
  }

  // ...
}

Add the debugger keyword to your code before calling getFiles, like this:
var file;
debugger;
getFiles("./",[], function(result){
    file = result;
    return file;
});

Before running the script, open chrome://inspect. Click on "Open dedicated DevTools for Node".
Run the script with the --inspect option, like this:
After running the script, it will stop and you can execute it gradually, understanding where the error is. In the debugger on the right-top there will be several buttons with different transition options, you need "Step", this is a dot and a straight arrow to the right. When you click on it, the current operation will be performed and the code will stop again at the next one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question