Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise - nested function doesn't works

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

like image 321
Webwoman Avatar asked Jul 14 '26 12:07

Webwoman


2 Answers

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))
like image 79
Barmar Avatar answered Jul 16 '26 04:07

Barmar


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);
});
like image 21
3ocene Avatar answered Jul 16 '26 04:07

3ocene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!