Async function returns Promise {<pending>}?

I have the following asynchronous function:

async function readFile () {
  let content = await new Promise((resolve, reject) => {
    fs.readFile('./file.txt', function (err, content) {
      if (err) {
        return reject(err)
      }
      resolve(content)
    })
  })

  console.log(content)
}

readFile()

This works great. It outputs the file buffer to the console as expected. But now, if I try to return the value instead:

async function readFile () {
  let content = await new Promise((resolve, reject) => {
    fs.readFile('./file.txt', function (err, content) {
      if (err) {
        return reject(err)
      }
      resolve(content)
    })
  })

  return content
}

console.log(readFile())

Now I get:

Promise { <pending> }

Why is this? Why can you use the value inside this function, but when you return it from the function, now is it Promise?

How do you actually use this in your normal workflow? For example, let's say I wanted to check if a file exists, then read in the file, and then update some database with the contents, the synchronous pseudocode will look something like this:

if (fileExists(path)) {
  buffer = readFile(path)
  updateDatabase(buffer)
}

3 . - async/await? , script, async?

async function doSomething () {
  if (fileExists(path)) {
    buffer = readFile(path)
    updateDatabase(buffer)
  }
}

( , , , , ).

+6
1

async , . readFile :

function readFile() {
  return new Promise((resolve, reject) => {
    fs.readFile('./file.txt', function (err, content) {
      if (err) {
        return reject(err)
      }
      resolve(content)
    })
  })
}

readFile await:

console.log(await readFile()) // will log your actual file contents.

, async , , async, , await :

async function doSomething () {
  try {  
    const fileCheck = await fileExists(path)

    if (fileCheck) {
      const buffer = await readFile(path)
      await updateDatabase(buffer)
      // Whatever else you want to do
    }
  } catch (err) {
    // handle any rejected Promises here.
  }
}
+5

Source: https://habr.com/ru/post/1017301/


All Articles