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

How to use the Typescript async / await function and return the default Typescript promises in the js FS node js module and call another function after resolving the promise.

Below 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 }; 
+5
source share
2 answers

At the moment, I think there is no other way to go with the wrapper function. Something like that:

 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 are several detailed discussions in node about promises.js: Each async function returns a Promise

+8
source

If you do not want to write Promise wrappers yourself, you can use async-file .

Using this code, you can look something like this:

 (async function () { //... await fs.writeFile(FILE_TOKEN, value); var data = await fs.readFile('gist'); // do something with your "gist" data here... })(); 
0
source

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


All Articles