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 function
frameCallback is resolve function
To put it all together, using new Promise(requestAnimationFrame)
- Promise constructor internally calls an executor (in this case
requestAnimationFrame). As requestAnimationFrame is called,
browser internally schedules it as a request for animation.
- When browser is ready to animate requested frame, it invokes a callback provided to
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
});