Can someone please explain what this function does? I understand how the requestAnimationFrame
executes before the paint and render within a frame, but I'm not really sure what's the utility of putting it inside a promise.
function nextFrame() {
return new Promise(requestAnimationFrame)
}
Promise constructor accepts a so called executor
function as it's first argument, which can be used to control promise execution flow. This function has two arguments: resolve
and reject
- these are functions you call to either resolve or reject a promise.
const promise = new Promise(function executor(resolve, reject) {
resolve();
// reject();
});
That executor
function is called internally automatically when you create a new promise using new Promise(executor)
.
Next, requestAnimationFrame requires a callback, which will be fired whenever a browser is ready to execute your frame code.
requestAnimationFrame(function frameCallback(timestamp) {
// ...frame code
});
If you try to impose requestAnimationFrame(frameCallback)
signature on top of executor(resolve, reject)
signature, then
requestAnimationFrame
is executor
functionframeCallback
is resolve
functionTo put it all together, using new Promise(requestAnimationFrame)
requestAnimationFrame
). As requestAnimationFrame
is called,
browser internally schedules it as a request for animation.requestAnimationFrame
. In our case resolve
serves as a callback. In addition resolve
will be passed with a timestamp from requestAnimationFrame
i.e. the promise will be resolved with a timestamp value.I guess this code can be used to Promise-ify requestAnimationFrame
, contstructed promise will be resolved as soon as requestAnimationFrame
callback is called.
const promise = new Promise(requestAnimationFrame);
promise.then(function frameCallback(timestamp) => {
// ... frame code
});