Shan Khan Shan Khan - 7 months ago 38
Javascript Question

How to use Typescript Async/ await with promise in Node JS FS Module

How to use Typescript async / await function and return typescript default promises in node js FS module and call other function upon promise resolved.

Following is the code :

if (value) {
tempValue = value;
fs.writeFile(FILE_TOKEN, value, WriteTokenFileResult);
}

function WriteTokenFileResult(err: any, data: any) {
if (err) {
console.log(err);
return false;
}
TOKEN = tempValue;
ReadGist(); // other FS read File call
};

Answer

For now I think there is no other way as to go with wrapper function. Something like this:

function WriteFile(fileName, data): Promise<void>
{
    return new Promise<void>((resolve, reject) =>
    {
        fs.writeFile(fileName, data, (err) => 
        {
            if (err)
            {
                reject(err);    
            }
            else
            {
                resolve();
            }
        });
    });        
}

async function Sample()
{
    await WriteFile("someFile.txt", "someData");
    console.log("WriteFile is finished");
}

There is some lengthy discussion here about promises in node.js: Every async function returns Promise

Comments