Promise.resolve 没有传入参数

Promise.resolve with no argument passed in

OpenUI5 code-base 我看到了这个片段:

// 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));

它看起来像 native Promise function is being used, with no argument being passed to it's resolve 函数,它接受一个:

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

因此,由于看起来承诺会立即解析并调用 then 的回调,可能 意图是 similar to:

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

...基本上,释放 JavaScript 运行 时间事件循环以完成其他事情(如渲染),然后立即返回回调?

我的问题是:

这是常见的模式吗?最佳实践?这两种方法都有 advantages/disadvantages 吗?

是的,Promise.resolve() 会立即满足您隐式传入的 undefined 值。回调仍然异步执行 - 很像您发布的 setTimeout 片段。

然而,正如代码中的注释所解释的那样,目的是不只是异步执行回调:

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

Promise 回调在超时或其他事件之前执行 运行,这些细微的时间差异有时很重要。鉴于任务循环的选择通常并不重要,不,这不是一种常见模式;但它是一个有效的模式,可以在您需要时完全满足您的需求。

我注意到这个 polyfill 中的技术:https://github.com/wicg/inert(带评论)

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);
});