Simple promise with async /await demo

  • by

Script

const simple_promise_demo = (a, b) => {
    return new Promise((resolve, reject) => {
        if (b !== 0)
        {
            resolve(a/b)
        }
        else
        {
            let problem = new Error(a + ' / ' + b + ' -> Cant divide by zero!')
            reject(problem)
        }
    })
}

const do_work = async () => {
    try {
        const result1 = await simple_promise_demo(3, 5)
        console.log(result1)
        const result2 = await simple_promise_demo(3, 0)
        console.log(result2)
    } catch (e) {
        console.log(e)
    }
    
}

do_work()

If a promise is rejected in the try block, the error message gets catched.

Result

node async-await.js 
0.6
Error: 3 / 0 -> Cant divide by zero!
    at Promise (/home/ubuntu/onews/playground/async-await.js:9:27)
    at new Promise (<anonymous>)
    at simple_promise_demo (/home/ubuntu/onews/playground/async-await.js:2:12)
    at doWork (/home/ubuntu/onews/playground/async-await-sij.js:26:31)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3