-1

I want to write a script that read a file and print some informations; the output of the code below is:

PRE runAsync
POST runAsync
POST asyncResult:
END
INSIDE FILE3 readFile callback function...
The script doesn't print the content of the file FILE3; where is the problem? I'm confusing about promise/async/await! I'm using nodejs and typescript.

import * as fs from "fs";
const FILE3 = "./sample3.txt";

async function readAsyncFile(FILE3: string): Promise<string> {
  //const orWithVariable = function readPromise() {
  let fileContent: string = "";
  fs.readFile(FILE3, "utf8", (err, data) => {
    console.log("INSIDE FILE3 readFile callback function...");
    if (err) fileContent = "Error reading FILE3";
    else fileContent = data;
  });
  return fileContent;
}

async function runAsync() {
  let asyncResult: string = await readAsyncFile(FILE3);
  console.log("POST asyncResult: " + asyncResult);
}
console.log("PRE runAsync");

runAsync().then(() => {
  console.log("END");
});

console.log("POST runAsync");

The expected output should be:

PRE runAsync
POST runAsync
POST asyncResult:
--> here the content of FILE3 END
INSIDE FILE3 readFile callback function...

NOTE: I'm trying to understand promise/await/async with nodejs and typscript; can anybody tell me where to start? Good and simple tutorials with lots of examples? Thanks.

user1
  • 556
  • 2
  • 6
  • 22

1 Answers1

1

Let's take a look at the async read:

async function readAsyncFile(FILE3: string): Promise<string> {
    let fileContent: string = "";
    ...
    return fileContent;
}

This function returns a string directly, but it should return a promise (I guess Typescript should have warned about this).

async function readAsyncFile(FILE3: string): Promise<string> {
    let fileContent = new Promise<string>((resolve, reject) => {
        // code here should resolve(data) or reject(error)
        ...
    })
    return fileContent
}

So just add fs.readFile inside and call those functions in the callback:

async function readAsyncFile(FILE3: string): Promise<string> {
    const fileContent = new Promise<string>((resolve, reject) => {
        // code here should resolve(data) or reject(error)
        fs.readFile(FILE3, "utf8", (err, data) => {
            console.log("INSIDE FILE3 readFile callback function...");
            if (err) reject("Error reading FILE3");
            else resolve(data);
        });
    })
    return fileContent
}
Lyth
  • 2,171
  • 2
  • 29
  • 37
  • thanks Lyth; but I'm confusing... does function with async keyword are interchangeable with functions that returns Promises? So why I have to create a promise inside a function with async keyword? – user1 Aug 30 '19 at 08:08
  • @Yellow75 it's only because `fs.readFile` uses callback convention. There are wrappers around this too, see for example [promisify answer](https://stackoverflow.com/a/46867579/949044) – Lyth Sep 07 '19 at 20:03