首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将对象作为输入使用Promise.all

如何将对象作为输入使用Promise.all
EN

Stack Overflow用户
提问于 2015-03-27 11:44:46
回答 16查看 46.3K关注 0票数 35

我一直在开发一个供我自己使用的小型2D游戏库,我遇到了一些问题。库中有一个名为loadGame的特殊函数,它将依赖项信息作为输入(资源文件和要执行的脚本列表)。下面是一个例子。

代码语言:javascript
运行
复制
loadGame({
    "root" : "/source/folder/for/game/",

    "resources" : {
        "soundEffect" : "audio/sound.mp3",
        "someImage" : "images/something.png",
        "someJSON" : "json/map.json"
    },

    "scripts" : [
        "js/helperScript.js",
        "js/mainScript.js"
    ]
})

资源中的每个项目都有一个键,游戏使用该键来访问特定的资源。loadGame函数将资源转换为promises对象。

问题是它试图使用Promises.all来检查它们是否都准备好了,但是Promise.all只接受迭代器作为输入-所以像我这样的对象是不可能的。

所以我尝试将对象转换为数组,这很有效,除了每个资源只是数组中的一个元素,并且没有键来标识它们。

下面是loadGame的代码:

代码语言:javascript
运行
复制
var loadGame = function (game) {
    return new Promise(function (fulfill, reject) {
        // the root folder for the game
        var root = game.root || '';

        // these are the types of files that can be loaded
        // getImage, getAudio, and getJSON are defined elsewhere in my code - they return promises
        var types = {
            jpg : getImage,
            png : getImage,
            bmp : getImage,

            mp3 : getAudio,
            ogg : getAudio,
            wav : getAudio,

            json : getJSON
        };

        // the object of promises is created using a mapObject function I made
        var resources = mapObject(game.resources, function (path) {
            // get file extension for the item
            var extension = path.match(/(?:\.([^.]+))?$/)[1];

            // find the correct 'getter' from types
            var get = types[extension];

            // get it if that particular getter exists, otherwise, fail
            return get ? get(root + path) :
                reject(Error('Unknown resource type "' + extension + '".'));
        });

        // load scripts when they're done
        // this is the problem here
        // my 'values' function converts the object into an array
        // but now they are nameless and can't be properly accessed anymore
        Promise.all(values(resources)).then(function (resources) {
            // sequentially load scripts
            // maybe someday I'll use a generator for this
            var load = function (i) {
                // load script
                getScript(root + game.scripts[i]).then(function () {
                    // load the next script if there is one
                    i++;

                    if (i < game.scripts.length) {
                        load(i);
                    } else {
                        // all done, fulfill the promise that loadGame returned
                        // this is giving an array back, but it should be returning an object full of resources
                        fulfill(resources);
                    }
                });
            };

            // load the first script
            load(0);
        });
    });
};

理想情况下,我希望以某种方式正确地管理资源的承诺列表,同时仍然为每个项目管理一个标识符。任何帮助都会很感谢,谢谢。

EN

回答 16

Stack Overflow用户

发布于 2018-05-21 01:10:38

如果您使用的是lodash库,您可以通过一个单行函数来实现:

代码语言:javascript
运行
复制
Promise.allValues = async (object) => {
  return _.zipObject(_.keys(object), await Promise.all(_.values(object)))
}
票数 14
EN

Stack Overflow用户

发布于 2015-03-27 13:13:39

首先:删除this usage is an antipattern这个Promise构造函数!

现在,来看看您的实际问题:正如您已经正确识别的那样,您缺少每个值的关键字。您将需要在每个promise中传递它,以便您可以在等待所有项之后重新构造对象:

代码语言:javascript
运行
复制
function mapObjectToArray(obj, cb) {
    var res = [];
    for (var key in obj)
        res.push(cb(obj[key], key));
    return res;
}

return Promise.all(mapObjectToArray(input, function(arg, key) {
    return getPromiseFor(arg, key).then(function(value) {
         return {key: key, value: value};
    });
}).then(function(arr) {
    var obj = {};
    for (var i=0; i<arr.length; i++)
        obj[arr[i].key] = arr[i].value;
    return obj;
});

更强大的库,如Bluebird,也会像Promise.props一样,将其作为助手函数提供。

此外,您不应该使用伪递归load函数。您可以简单地将promises链接在一起:

代码语言:javascript
运行
复制
….then(function (resources) {
    return game.scripts.reduce(function(queue, script) {
        return queue.then(function() {
            return getScript(root + script);
        });
    }, Promise.resolve()).then(function() {
        return resources;
    });
});
票数 12
EN

Stack Overflow用户

发布于 2018-08-07 16:30:59

实际上,我为此创建了一个库,并将其发布到github和npm:

https://github.com/marcelowa/promise-all-properties

https://www.npmjs.com/package/promise-all-properties

唯一的问题是,您需要为对象中的每个promise分配一个属性名称……下面是自述文件中的一个示例

代码语言:javascript
运行
复制
import promiseAllProperties from 'promise-all-properties';

const promisesObject = {
  someProperty: Promise.resolve('resolve value'),
  anotherProperty: Promise.resolve('another resolved value'),
};

const promise = promiseAllProperties(promisesObject);

promise.then((resolvedObject) => {
  console.log(resolvedObject);
  // {
  //   someProperty: 'resolve value',
  //   anotherProperty: 'another resolved value'
  // }
});
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29292921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档