Promise.resolve with no argument passed in

2019-04-07 05:56发布

问题:

In the OpenUI5 code-base I came across this snippet:

// Wait until everything is rendered (parent height!) before reading/updating sizes.
// Use a promise to make sure
// to be executed before timeouts may be executed.
Promise.resolve().then(this._updateTableSizes.bind(this, true));

It looks like the native Promise function is being used, with no argument being passed to it's resolve function which takes an:

Argument to be resolved by this Promise. Can also be a Promise or a thenable to resolve.

So, since it looks like the promise would simply immediately resolve and invoke then's callback, perhaps the intent is similar to:

var self = this;
setTimeout(function() {
    self._updateTableSizes.bind(self, true)
}, 0);

...basically, freeing the JavaScript run-time event-loop to finish other things (like rendering) and then come right back to the callback?

My question is:

Is this a common pattern? Best-practice? Are there any advantages/disadvantages to either approach?

回答1:

Yes, Promise.resolve() does immediately fulfill with the undefined value that you implicitly passed in. The callback is still executed asynchronously - quite like in the setTimeout snippet you posted.

However, as the comment in the code explains, the intent is not just to execute the callback asynchronously:

Use a promise to make sure to be executed before timeouts may be executed.

Promise callbacks do run before timeouts or other events, and these subtle timing differences are sometimes important. Given that choice of the task loop is usually not important, No this is not a common pattern; but it is a valid pattern that does exactly what you need when you need it.



回答2:

I noticed the technique in this polyfill: https://github.com/wicg/inert (with comment)

const newButton = document.createElement('button');
const inertContainer = document.querySelector('[inert]');
inertContainer.appendChild(newButton);
// Wait for the next microtask to allow mutation observers to react to the DOM change
Promise.resolve().then(() => {
expect(isUnfocusable(newButton)).to.equal(true);
});