stefanpenner / es6-promise

A polyfill for ES6-style Promises
MIT License
7.3k stars 593 forks source link

It's difference between native and shim #333

Open david-ni opened 6 years ago

david-ni commented 6 years ago

when I run the following code in browser(chrome v66) that support promise native

let promiseA = new Promise(function(resolve){ resolve('A') }),
    promiseB = new Promise(function(resolve){ resolve(promiseA) }),
    promiseC = new Promise(function(resolve){ resolve('C') });

promiseB.then((arg)=>{ console.log(arg); });
promiseC.then((arg)=>{ console.log(arg); });

the result is C A but when I run the same code with es6-promise,the result is reverse: A C which one is right?

Aqours commented 6 years ago

The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; if the value was a promise, that object becomes the result of the call to Promise.resolve; otherwise the returned promise will be fulfilled with the value.

Unlike old-style passed-in callbacks, a promise comes with some guarantees:

  • Callbacks will never be called before the completion of the current run of the JavaScript event loop.
  • Callbacks added with .then even after the success or failure of the asynchronous operation, will be called, as above.
  • Multiple callbacks may be added by calling .then several times, to be executed independently in insertion order.
let promiseA = new Promise(function(resolve){ resolve('A') }),
    promiseC = new Promise(function(resolve){ resolve('C') });

promiseA.then(arg => arg).then((arg)=>{ console.log(arg); });
promiseC.then((arg)=>{ console.log(arg); });

According to MDN docs, your code equal to above code. So the result is C A which is correct, and it's a bug of es6-promise.