Simple promise demo

  • by

Function

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)
        }
    })
}

Executing with valid parameters

simple_promise_demo(3, 5).then((result) => {
    console.log(result)
}).catch((e) => {
    console.log(e)
})

Returns

node promise.js 
0.6

Executing with invalid parameters

simple_promise_demo(3, 0).then((result) => {
    console.log(result)
}).catch((e) => {
    console.log(e)
})

Returns

node promise.js 
Error: 3 / 0 -> Cant divide by zero!
    at Promise (/home/ubuntu/onews/playground/promise.js:9:27)
    at new Promise (<anonymous>)
    at simple_promise_demo (/home/ubuntu/onews/playground/promise.js:2:12)
    at Object.<anonymous> (/home/ubuntu/onews/playground/promise.js:15:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)