简体   繁体   中英

requestAnimationFrame inside a Promise

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 function
  • frameCallback is resolve function

To put it all together, using new Promise(requestAnimationFrame)

  1. Promise constructor internally calls an executor (in this case requestAnimationFrame ). As requestAnimationFrame is called, browser internally schedules it as a request for animation.
  2. 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 ie 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
});

...or simply:

await new Promise(requestAnimationFrame);
// <-- body of the former frameCallback function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM