Search code examples
javascriptfunctionpromisees6-promise

JavaScript new Promise shorthand


I'm wondering if there's any shorthand to create a promise in JavaScript, or any way to add .then to a normal function. Example:

dbl = a => a | 0 ? a * 2 : !1;
dbl(10).then(r => r / 2); // should be original number entered.

I want to either make the dbl function instead be a promise, but stay fairly short. Or to add some sort of protoype to function that would let me do something like the above code.


Solution

  • I don't know why you would want to do this, but you can wrap any value in a promise by writing Promise.resolve(value). You can attach then callbacks to the resulting promise.

    dbl = a => a|0 ? a*2 : !1
    Promise.resolve(dbl(10)).then(r => r/2) //should be original number entered.