Search code examples
javascriptecmascript-6es6-promise

Following example of JavaScript Promise giving error


I'm creating a promise which will take an input and then return (+3) to it. Then I want to print the result. Why am I getting the error?

var prom = new Promise((item) => item+3);

prom(5).then(console.log(result));

I'm new to Promises. Please help.


Solution

  • First of all, you do not supply a promise with arguments. If you want to create a promise with return value, you need to create a function that returns a promise.

    Second, then takes a function and will provide it with the result argument that you can use in your console.log.

    // var prom = new Promise((item) => item+3);
    const prom = item => new Promise((resolve, reject) => resolve(item + 3));
    
    // prom(5).then(console.log(result));
    prom(5).then(result => console.log(result));