Skip to content

Instantly share code, notes, and snippets.

@franck34
Created February 2, 2019 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franck34/c08eca6379c60f6694468341a7442e45 to your computer and use it in GitHub Desktop.
Save franck34/c08eca6379c60f6694468341a7442e45 to your computer and use it in GitHub Desktop.
nodejs async await for noob like me
const { promisify } = require("util");
function Foo() {
this.one = promisify(
function(value, callback) {
setTimeout(() => {
console.log("one", value);
callback(null, true);
}, 500);
}
);
this.two = promisify(
function(value, callback) {
setTimeout(() => {
console.log("two", value);
callback(null, true);
}, 500);
}
);
this.err = promisify(
function(value, callback) {
callback("hooo shiiit");
}
);
return this;
}
async function go() {
let foo = new Foo();
try {
await foo.one("myone");
await foo.two("mytwo");
await foo.err("hu");
} catch(e) {
console.log("error: ",e);
}
}
go();
@franck34
Copy link
Author

franck34 commented Feb 2, 2019

const { promisify } = require("util");

function Foo() {

    let self = this;

    this.show = (value, callback) => {
        setTimeout(() => {
            console.log(value);
            callback(null, true);
        }, 500);
    }

    this.err = (value, callback) => {
        callback(value);
    }

    this.show = promisify(this.show);
    this.err = promisify(this.err);

    return this;
}


async function start() {
    let foo = new Foo();
    try {
        await foo.show("one");
        await foo.show("two ...");
        await foo.err("you will NOT pass");
        await foo.show("three !");
    } catch(e) {
        console.log("error: ",e);
    }
}

start();

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