I'm wondering why the following code doesn't works, after all it is just nested function:
var calculus = new Promise((resolve, reject) => (resolve) => resolve(3))
var calculus2 = new Promise((resolve, reject) => {
() => resolve(4)
})
calculus.then((result) => console.log(result))
calculus2.then((result) => console.log(result))
any hint would be great, thanks
You need to invoke the nested function.
var calculus = new Promise((resolve, reject) => ((resolve) => resolve(3))(resolve))
calculus.then((result) => console.log(result))
If you don't want to repeat (resolve) at the end, you can get rid of the parameter to the nested function.
var calculus = new Promise((resolve, reject) => (() => resolve(3))())
calculus.then((result) => console.log(result))
In either case, there's not really much point to the nested function, you can just write:
var calculus = new Promise((resolve, reject) => resolve(3))
calculus.then((result) => console.log(result))
Note: Barmar was faster with their answer, and reading it, I think I misinterpreted what you were asking a bit. However, I'm still going to post this as it might help clarify exactly what's going on in your example.
Your first line,
var calculus = new Promise((resolve, reject) => (resolve) => resolve(3))
Returns something comparable to an object like this (although it's quite different behind the scenes):
{
then: function(callback) {
callback(function (resolve) {
resolve(3);
});
}
}
So to use this, you would want to do something like this:
calculus.then((resolver) => {
resolver(function (value) {
console.log(value); // 3
});
});
I think what you're likely meaning to do is this:
const calculus = new Promise((resolve, reject) => resolve(3));
calculus.then((result) => console.log(result))
Remember that () => {} is similar (though not quite the same) to function() {}, and () => something is like function () { return something }
So your original code is like this
var calculus = new Promise(function (resolve, reject) {
return function (resolve) {
resolve(3)
};
});
When you want
var calculus = new Promise(function (resolve, reject) {
resolve(3);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With