async function returns Promise { }?

后端 未结 1 2022
醉梦人生
醉梦人生 2021-01-05 08:44

I have the following async function:

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


        
相关标签:
1条回答
  • 2021-01-05 08:57

    All async functions return a promise as was mentioned in the comments. You could therefore re-write your readFile function like this:

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

    You would then consume the return value of readFile via await:

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

    The usual workflow with this paradigm is to break your async operations into separate functions that each return a promise, and then run them all inside a broader async function, much like you suggest, but with awaits and some error handling like so:

    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.
      }
    }
    
    0 讨论(0)
提交回复
热议问题