Is it possible to use ASYNC AWAIT when receiving a PROMISE return?

Asked

Viewed 42 times

0

I would like to know if it is possible to receive the return of a Promise using async await?

I created a file where I read a file and return the string of that file, to receive this variable, in my other function I created a function ASYNC await, but apparently it is not waiting for this action to be executed to give the console.log() and that makes my variable come Undefined, follow the code.

APP.JS

const ManagerFile = require('./ManagerFile');

var managerFile = new ManagerFile();

async function readFile() {

    var result = await managerFile.Read('./users.csv');

    console.log(result)

}

readFile();

Managerfile.js

const fs = require('fs');
const util = require('util');

class ManagerFile {

    constructor() {

        this.readFile = util.promisify(fs.readFile);

    }

    Read(pathFile) {

        this.readFile(pathFile, { encoding: 'utf-8' }).then((data, err)=>{

            return data;

        });

    }

}

module.exports = ManagerFile;

Problem

console.log(result) - UNDEFINED

  • In the method .Read(), missing a return before the this.readFile.

  • Unfortunately I still return Undefined

1 answer

0

I think you need to actually return to Promise. Something more or less like this:

const returnAPromise = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve("ASYNC DATA");
    },1000);
  });
};

const getPromise = async () => {
  console.log(`Calling returnAPromise...`);
  const result = await returnAPromise();
  console.log(`Result: ${result}`);
};

getPromise();

Browser other questions tagged

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