Как использовать promise на vue.js?

Фрагмент моего кода, если не использовать промис, то не удается вытащить данные корректно

   Promise((resolve) => {     
                fetch('/currentDir1',{
                    method: 'POST',
                    mode: 'cors',
                    headers: {
                        'Content-Type': 'application/json',                    
                    },
                    body: JSON.stringify(elem)                
                    })
                    .then(response => response.json())    
                    .then(json => this.helper = json)
                    .then(json =>  this.$emit("newvalue", json)) 
                    console.log("helper");
                    console.log(this.helper);
                    resolve("result");
             });

Обработчик со стороны сервера

router.post('/currentDir1',(req, res) =>{  
    console.log("POST");
    
    let body = "";   
    let pathToFile = "";
    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){
                foo(dir, './data/firstScreen.json');
                pathToFile = './data/firstScreen.json';
                res.sendFile(path.resolve('./data/firstScreen.json'));
            }else{
                console.log('aaaa');
                Foo(dir, './data/secondScreen.json');
                pathToFile = './data/firstScreen.json';
                res.sendFile(path.resolve('./data/secondScreen.json'));
                
            }        
        }
        // res.json({ message: 'goodbye'})   
        res.json(path.resolve(pathToFile));     
    });        
    res.sendFile(path.resolve(pathToFile));
})

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

Автор решения: dmitriy_vlz

ну я попробовал "на коленке" накидать, попробуй.

 async nameOfMethod(){
  const responce = await  fetch('/currentDir1',{
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',                    
    },
    body: JSON.stringify(elem)                
    });
  
    const json = await responce.json()
    this.helper = json
    this.$emit("newvalue", json)
}
→ Ссылка
Автор решения: eri

ваш промис сразу отправляет resolve("result"); в переменную. чтоб отправить в переменную текст "result", то нужно это тоже указать в цепочке then.

Фрагмент моего кода, если не использовать промис, то не удается вытащить данные корректно

var self = this; 
Promise((resolve) => {
            fetch('/currentDir1',{
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',                    
                },
                body: JSON.stringify(elem)                
                })
                .then(response => response.json())    
                .then(json => self.helper = json)
                .then(json =>  self.$emit("newvalue", json))
                .then((x) => {
                  console.log("helper");
                  console.log(self.helper);
                  resolve("result");
                }
         });

Ещё добавил тут замыкание на this потому что в колбэках оно не всегда получается то что нужно.

→ Ссылка