0

Not quite sure I've understood async promises, but shouldnt I be able to call the first function below without .then?

const fs = require('fs')
const lineReader = require('readline')

exports.isEnglish = async (item) => {
  return new Promise((resolve, reject) => {
    let lr = lineReader.createInterface({
      input: fs.createReadStream('words.txt')
    })
    lr.on('line', (line) => {
      if (item.toLowerCase() === line.toLowerCase()) {
        resolve(true)
      }
    })
    lr.on('end', (line) => {
      reject(false)
    })
  })
}

then calling it like this:

const english = require('./index')

console.log(english.isEnglish('ZZZ')
  .then((result) => {
    console.log(result)
  })
  .catch((err) => {
    console.log(err)
  })
)
  • 2
    `exports.isEnglish = async (item) => {` you don't need `async` keyword ehre – mehulmpt Apr 15 '18 at 13:02
  • What @mehulmpt said: https://stackoverflow.com/questions/47880415/what-is-the-benefit-of-prepending-async-to-a-function-that-returns-a-promise – Bergi Apr 15 '18 at 13:33

1 Answers1

1

The function you defined is async and returns a promise. To invoke it in the same async-await syntax, the enclosing scope needs to have the async keyword and then you invoke the function in the following way:

const result = await asyncFunction();
Abslen Char
  • 3,071
  • 3
  • 15
  • 29
Gilad Bar
  • 1,302
  • 8
  • 17