对象键映射 - 如何暂停迭代

时间:2017-08-29 10:36:02

标签: javascript html5 dictionary

我正在做一个简单的html5游戏。

        Object.keys(gameConfig.playerElems).map((e) =>{

        let img = gameConfig.playerElems[e];
        let name = e;
        let imgObj;

        imgObj = new Image();
        imgObj.src = img;

        imgObj.onload = () => {
            playerElemsCounter++;
            drawPlayer(imgObj);
        }
    });

是否可以在加载.map()时暂停imgObj次迭代?

1 个答案:

答案 0 :(得分:2)

  

是否可以在加载imgObj时暂停.map()迭代?

没有。因此,您使用异步循环。这是一个例子,见评论:

// A named IIFE
(function iteration(keys, index) {
    // Get info for this iteration
    let name = keys[index];
    let img = gameConfig.playerElems[name];
    let imgObj = new Image();
    // Set event callbacks BEFORE setting src
    imgObj.onload = () => {
        playerElemsCounter++;
        drawPlayer(imgObj);
        next();
    };
    imgObj.onerror = next;
    // Now set src
    imgObj.src = img;

    // Handles triggering the next iteration on load or error
    function next() {
        ++index;
        if (index < keys.length) {
            iteration(keys, index);
        }
    }
})(Object.keys(gameConfig.playerElems), 0);

但是,正如Haroldo_OK所指出的那样,在请求下一个图像之前,这将等待一个图像加载,这不仅是不必要的,而且是有害的。相反,请求所有人,在收到它们时绘制它们,然后继续。您可以通过给自己一个返回承诺的加载函数来做到这一点:

const loadImage = src => new Promise((resolve, reject) => {
    const imgObj = new Image();
    // Set event callbacks BEFORE setting src
    imgObj.onload = () => { resolve(imgObj); };
    imgObj.onerror = reject;
    // Now set src
    imgObj.src = src;
});

然后:

// Load in parallel, draw as we receive them
Promise.all(Object.keys(gameConfig.playerElems).map(
    key => loadImage(gameConfig.playerElems[key])
            .then(drawPlayer)
            .catch(() => drawPlayer(/*...placeholder image URL...*/))
)
.then(() => {
    // All done, if you want to do something here
});
// No need for `.catch`, we handled errors inline

如果想要(由于某种原因)在等待上一个图像时等待加载下一个图像,那么loadImage函数可以以不同的方式使用,例如经典承诺reduce模式:

// Sequential (probably not a good idea)
Object.keys(gameConfig.playerElems).reduce(
    (p, key) => p.then(() =>
                    loadImage(gameConfig.playerElems[key])
                    .then(drawPlayer)
                    .catch(() => drawPlayer(/*...placeholder image URL...*/))
                )
    ,
    Promise.resolve()
)
.then(() => {
    // All done, if you want to do something here
});
// No need for `.catch`, we handled errors inline

...或使用ES2017 async / await

// Sequential (probably not a good idea)
(async function() {
    for (const key of Object.keys(gameConfig.playerElems)) {
        try {
            const imgObj = await loadImage(gameConfig.playerElems[name]);
            playerElemsCounter++;
            drawPlayer(imgObj);
        } catch (err) {
            // use placeholder
            drawPlayer(/*...placeholder image URL...*/);
        }
    }
})().then(() => {
    // All done
});
// No need for `.catch`, we handled errors inline

旁注:如果您不是A,则无需使用map A)从回调中返回一个值以用于填充新数组map创建,以及B)使用数组{ {1}}返回。如果您不这样做,请使用map(或forEachfor循环播放。