-3

The following code use Destructuring:

var obj = {
  fun1:function() { console.log('Working') }
};

obj = { fun1:function(){ console.log("Replaced Working")} }

obj.fun1();

//output:
//Replaced Working

Does the following Promise do the same?

var pr = Promise.resolve({then:function(resolve){
  resolve(20);
  }
})


pr.then(function(v){
  console.log(v);
})

that's mean,pr is equal Promise object that,its then method changed to:

function(resolve){
  resolve(20);
}

and finally,pr.then(function(v){...} produces result.if don't use of Destructuring ,so why there is passed then property in Promise.resolve?

Ehsan
  • 12,655
  • 3
  • 25
  • 44
  • Could you change your question title? It really isn't clear what it means. I don't understand "Has been used destructuring". – zero298 Jul 30 '18 at 16:10
  • 3
    There is no destructuring here – Jonas Wilms Jul 30 '18 at 16:10
  • You're just passing a thenable object literal to `Promise.resolve()` this is a documented use case. It's difficult to know what you are asking. – Mark Jul 30 '18 at 16:15
  • No, it does not do the same obviously: your first snippet logs `Replaced Working`, while your second snippet (asynchronously) logs `20`. – Bergi Jul 30 '18 at 16:21

1 Answers1

2

The following code use Destructuring

No it does not. Destructuring would be

 const { fun1 } = obj;
 fun1();

You are just rewriting a property.

Does the following Promise do the same?

No it does not. resolve is an internal function of the promise constructor that then calls all the functions passed into thens. There is no property rewritten at all.

why there is passed then property in Promise.resolve?

I don't know, that makes no sense at all. If you do:

 const pr = Promise.resolve(42);
 pr.then(console.log) // 42

If you pass an object in, it will resolve to that object:

 const pr = Promise.resolve({ some: "thing" });
 pr.then(console.log); // { some: thing }

If that object has a then method it is called a thenable object and the promise will follow that function assuming is has a signature of function(onFulfill, onReject). This is what your last example it doing.

Mark
  • 90,562
  • 7
  • 108
  • 148
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151