Как получить корректные данные после вызова функции?

Вот мой код. Смысл в том, что я делаю запрос на сервер и в ответ хочу, чтобы мой json файл был перезаписан и отправлен назад. Как результат файл перезаписывается, но данные приходят старые (до перезаписи). Возможно тут дело в асинхроности и промисах, но я не знаю как это исправить. Помогите, пожалуйста

 clickOnRow: function(elem, whichScreen){
          this.clicks++   
          if(this.clicks === 1) {
            var self = this
            this.timer = setTimeout(function() {            
            console.log("одинарный");                 
              self.clicks = 0
            }, this.delay);
          } else{
             clearTimeout(this.timer);
             console.log("двойной");

             console.log(elem);
             
             elem['whichScreen']  = whichScreen;    
            //  console.log(this.helper);
            //  this.nameOfMethod(elem);
             this.clicks = 0; 
            fetch('/currentDir1',{
                    method: 'POST',
                    mode: 'cors',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'                 
                    },
                    body: JSON.stringify(elem)                
                    })
                    // .then(response => console.log(response))  
                    .then(response => response.json())    
                    .then(json => this.helper = json.table)
                    .then(json => console.log(json))
                    
                    .then(this.$emit("newvalue", this.helper, whichScreen)) 
             
                                      
          }         
        },
router.post('/currentDir1', (req, res) =>{  
        console.log("POST");
        const fs = require('fs');
        let body = "";   
        let pathToFile = "";
        console.log(req.body);        
        
        req.on("data", function (data) {
            body += data;
        });
        
        req.on("end", function(currentData) {
            console.log(JSON.parse(body));
            currentData = JSON.parse(body);
            
    
            if(currentData.sizeOrType === "<папка>"){
                let dir = currentData.dir + currentData.fileName;
                // dir = "C:\\totalcmd";
                console.log(dir);                
                if(currentData.whichScreen){
                    console.log(currentData.whichScreen);                    
                    foo(dir, './data/firstScreen.json');
                    pathToFile = './data/firstScreen.json';                  
                    var json1 = JSON.parse(fs.readFileSync('./data/firstScreen.json', 'utf8'));
                
                    console.log(json1);                 
                    res.json(json1);

                   
                }else{
                    console.log('aaaa');
                    foo(dir, './data/secondScreen.json');
                    pathToFile = './data/firstScreen.json';
                    res.sendFile(path.resolve('./data/secondScreen.json'));
                    
                }        
            }
            
        });
           
       
    })

функция foo() которая отвечает за запись данных внутрь отправляемого файла

const fs = require('fs');

var Foo = async function(dir, pathToFile){
    let Mode = require('stat-mode'); // проверка дириктори или файл
    let temp; //вспомогательная переменная 
    let jsonFile = { 
        table: []
     };

     console.log("FOO WAS STARTED");
    
    fs.readdir(dir, function(err, items) {   // Вроде работает :)
        for (let i=0; i<items.length; i++) { //массив всех файлов текущей директории       
            try{                  
                fs.stat(dir +"\\"+ items[i], function(err, stats){
                        // console.log(dir +"\\"+ items[i]);
                        try{
                            let mode = new Mode(stats); // определяем папка или файл             
                            if(mode.isDirectory()){
                            temp = "<папка>";
                            } else{
                                temp = stats.size.toString() + " байт";
                            }                
                            jsonFile.table.push({icon:i, fileName:items[i], sizeOrType: temp , dateOfChange: stats.mtime, dir: dir}); //добавляем данные                    
                            await fs.writeFile(pathToFile, JSON.stringify(jsonFile), (err)=>{
                                if(err) console.log("error");
                            });
                        }
                        catch(e){
                            console.log(e);
                        }
                });
            }
            catch(e){                
                console.log(e);
                continue;
            }        
        }    
    });
}




// var Foo = async function(dir, pathToFile){
//     let Mode = require('stat-mode'); // проверка дириктори или файл
//     let temp; //вспомогательная переменная 
//     let jsonFile = { 
//         table: []
//      };

//      console.log("FOO WAS STARTED");
    
//     fs.readdir(dir, function(err, items) {   // Вроде работает :)
//         for (let i=0; i<items.length; i++) { //массив всех файлов текущей директории       
//             if(items[i].indexOf("System Volume Information")!= -1 || items[i].indexOf("hiberfil")!= -1 || items[i].indexOf("pagefile")!= -1 || items[i].indexOf("MSOCache")!= -1 || items[i].indexOf("swapfile")!= -1 || items[i].indexOf("Recovery")!= -1){
//                 continue;
//             }                   
//             fs.stat(dir +"\\"+ items[i], function(err, stats){
//                     console.log(dir +"\\"+ items[i]);
//                     if(err) throw err;
//                     let mode = new Mode(stats); // определяем папка или файл             
//                     if(mode.isDirectory()){
//                     temp = "<папка>";
//                     } else{
//                         temp = stats.size.toString() + " байт";
//                     }                
//                     jsonFile.table.push({icon:i, fileName:items[i], sizeOrType: temp , dateOfChange: stats.mtime, dir: dir}); //добавляем данные                    
//                     await fs.writeFile(pathToFile, JSON.stringify(jsonFile), (err)=>{
//                         if(err) console.log("error");
//                     });
//             });        
//         }    
//     });
// }

module.exports = Foo;

Ответы (0 шт):