如何将 requestAnimationFrame 与 Promise 一起使用

SER*_*ERG 5 javascript es6-promise

我想将requestAnimationFrame与Promise一起使用,所以我可以这样使用它

opacityToggle("layername",0).then(i=>"do some stuff after animation ends")
Run Code Online (Sandbox Code Playgroud)

,但不确定如何执行此操作。这是我的代码:

opacityToggle("layername",0).then(i=>"do some stuff after animation ends")
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

虽然 @Terry 有一个简单的解决方案,将所有内容都包装在 Promise 构造函数中,但如果您仅 Promise 调用本身,那么您将获得 Promise 的真正力量requestAnimationFrame

async function opacityToggle(layerName, opacity) { /*
^^^^^ */
    if (!layerName) return;

    var s = 0;
    while (s < 1) {
//  ^^^^^
        s += 0.01
        s = +s.toFixed(2)
        console.log('s', layerName, s, opacity);
        map.setPaintProperty(layerName, 'fill-opacity', s);

        await new Promise(resolve => {
//      ^^^^^
            requestAnimationFrame(resolve);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你不能使用async/await和/或想用递归方法来做到这一点,那就是

function opacityToggle(layerName, opacity) {
    if (!layerName) return Promise.resolve();

    var s = 0;
    return animate();

    function animate() {
        if (s < 1) {
            s += 0.01
            s = +s.toFixed(2)
            console.log('s', layerName, s, opacity);
            map.setPaintProperty(layerName, 'fill-opacity', s);
            return new Promise(resolve => {
//          ^^^^^^
                requestAnimationFrame(resolve);
            }).then(animate);
//            ^^^^^^^^^^^^^^
        } else {
            return Promise.resolve();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `return new Promise(requestAnimationFrame).then(animate);` 就可以了;-) (2认同)