Skip to content

Instantly share code, notes, and snippets.

@oxr463
Created February 26, 2020 23:41
Show Gist options
  • Save oxr463/4b8768a4e927b6d03e00e408b3da9bf5 to your computer and use it in GitHub Desktop.
Save oxr463/4b8768a4e927b6d03e00e408b3da9bf5 to your computer and use it in GitHub Desktop.
Escape async mode in JavaScript
#!/usr/bin/env node
# SPDX-License-Identifier: MIT
"use strict";
const fs = require("fs");
function main() {
let path = "test.txt";
(async () => {
let x = await handlePromise(path);
console.log(x);
})();
return 0;
}
async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf-8", (err, data) => {
if (err) {
console.log("[*]\tFile Bad.");
reject(err);
} else
resolve(data);
});
});
}
async function handlePromise(path) {
let x = await readFile(path);
return x;
}
main();
Hello World
@oxr463
Copy link
Author

oxr463 commented Feb 26, 2020

@neverrend, inside of that anonymous async function, instead of console.log(), I need to use return x;. Is this possible?

@oxr463
Copy link
Author

oxr463 commented Feb 27, 2020

@oxr463
Copy link
Author

oxr463 commented Feb 27, 2020

@neverrend, inside of that anonymous async function, instead of console.log(), I need to use return x;. Is this possible?

Also, we need to export readFile for use in another file. For example, first rename index.js to foo.js, then append the following line to the file,

exports.readFile = readFile;

Then in bar.js, include the contents and execute from there,

var foo = require("./foo");

foo.readFile("test.txt");

@oxr463
Copy link
Author

oxr463 commented Mar 5, 2020

I figured it out.

Here are some incomplete snippets,

// Fetching data from MongoDB via Mongoose
router.post("/", function(req, res, next) {
  async.waterfall(
    [
        async function(result, cb) {
            await query.findOne(function(err, data) {
              // action
            }
        }
    ]
  );
}

// Storing data
try {
    let save_data = await new_data.save();
    if (save_data) {
        // action
    }
} catch (err) {
    console.log(err);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment