admin管理员组

文章数量:1422453

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

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)
}
Share Improve this question asked Apr 3, 2020 at 17:39 AdamAdam 1011 silver badge7 bronze badges 1
  • 3 The accepted answer gives a great explanation of the mechanics. I think one big motivation would be that you can write await nextFrame(); inside an async function, e.g. at the top of a loop that should run once per animation step. – Matthias Fripp Commented Feb 4, 2021 at 17:31
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptrequestAnimationFrame inside a PromiseStack Overflow