arevilla009
arevilla009

Reputation: 453

How to return promise value JS

I'm trying to return a value obtained in a promise statement and I'm getting continuously Promise { undefined }, someone knows how to do it correctly? When I render the .ejs file with the data it get's anything.

// /documents/vocabulary file
async function transformar() {
    return new Promise(resolve => {
        fs.readFile('src/documents/Vocabulary2.txt', 'utf8', function(error, data) {
            if (data) {
                var d = data.split('\n');
                var a = []
                for (let i=0; i<d.length; i++) {
                    a.push({
                        eng: d[i].split('-')[0].trim(),
                        esp: d[i].split('-')[1].trim()
                    })
                }

                a.sort(dynamicSort('eng'));
                resolve(a);
            }
        });
    });
}

//index.js file
const vocabulary = require('./documents/vocabulary');
const myFunction = async () => {
    const data = await vocabulary.transformar();
    return data;
}
const vocab = myFunction();
console.log(vocab)

app.use('/', function(req,res){
    res.render(path.join(__dirname+'/Vocabulary.ejs'), {vocabulary_data: vocab});
});

enter image description here

Thanks for reading!

Upvotes: 0

Views: 2471

Answers (3)

Terry
Terry

Reputation: 66218

First of all, your transformar() method does not actually return a promise. Make sure you do that first:

function transformar() {
    return new Promise((resolve, reject) => {
        fs.readFile('src/documents/Vocabulary2.txt', 'utf8', function(error, data) {
            if (data) {
                var d = data.split('\n');
                var a = []
                for (let i=0; i<d.length; i++) {
                    a.push({
                        eng: d[i].split('-')[0].trim(),
                        esp: d[i].split('-')[1].trim()
                    })
                }

                a.sort(dynamicSort('eng'));
                resolve(a);
            } else {
                reject();
            }
        });
    });
}

Here are some suggestions:

  • You don't need to use async, since you already return a promise in the method now
  • All code paths should end up in reject() or resolve(), to avoid memory leaks (like what Thomas suggested in the comment below)

Now, back to the issue of getting data out of your promise: as there is no support for top-level await, so you need to either chain a .then() from the returned promise:

vocabulary.transformar().then((data) => console.log('data', data));

... or use await in an IIFE:

(async () => {
    const data = await vocabulary.transformar();
    console.log('data', data);
})();

If the Promise is being executed in a function, then you can simply use await:

const myFunction = async () => {
    const data = await vocabulary.transformar();
    console.log('data', data);
}

myFunction();

Upvotes: 3

Sarah Dayan
Sarah Dayan

Reputation: 468

Your asynchronous function isn't returning anything. Also, the fs.readFile function doesn't return promises, it takes a callback. You should wrap it within a promise and resolve it with your final value.

function transformar() {
  return new Promise(function (resolve, reject) {
    fs.readFile(
      'src/documents/Vocabulary2.txt',
      'utf8',
      function (error, data) {
        if (data) {
          //format data on array-dict
          var d = data.split('\n');
          var a = [];
          for (let i = 0; i < d.length; i++) {
            a.push({
              eng: d[i].split('-')[0].trim(),
              esp: d[i].split('-')[1].trim(),
            });
          }
          //sort data
          a.sort(dynamicSort('eng'));

          resolve(a);
        } else {
          reject(new Error('No data was found.'));
        }
      }
    );
  });
}

transformar()
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err);
  });

Upvotes: 1

Mayur Kukadiya
Mayur Kukadiya

Reputation: 2747

You should try this code :

async transformar() {
return new Promise((resolve, reject) => {
  console.log('Sorting data');
  fs.readFile('src/documents/Vocabulary2.txt', 'utf8', async (error, data) => {
    if (data) {
      //format data on array-dict
      var d = data.split('\n');
      var a = []
      for (let i = 0; i < d.length; i++) {
        a.push({
          eng: d[i].split('-')[0].trim(),
          esp: d[i].split('-')[1].trim()
        })
      }
      //sort data
      await a.sort(dynamicSort('eng'));
      resolve(a);
    }
  });
})
}

var data;
vocabulary.transformar().then(result=>{
data = result;
console.log('data', data);
});

Upvotes: 1

Related Questions