javascript - 异步 promise 的问题

标签 javascript asynchronous promise

我正在尝试从查询字符串中获取匹配实体的列表。我正在使用 s3 来存储我的对象。

问题是解决“主要 promise ”的 promise 是 ansych 仅在给定 setTimeOut 时返回数组。否则返回 [undefined, undefined...]

我的代码是这样的:

getEntities: (type, offset, limit, query) => {
    return new Promise((resolve, reject) => {

        seekKeys(type, offset, limit, query)
            .then((response) => {

                let entities = [];


                if (response.hasBeenFiltered) { // This is not used yet. 
                    for (let i = offset; i < response.keys.length && i < offset + limit; i++) {
                        entities.push(matchInstance(instance))
                    }

                    resolve(entities)

                } else { // here is where my issue's at.
                    console.log("Keys found: " + response.keys.length)
                    parseQuery(type, query)
                        .then((conditions) => {

                            let matches = response.keys.map((key) => {
                                readEntity(key).then((instance) => {
                                    logger.debug(instance); // logs instances.
                                    matchInstance(instance, conditions)
                                        .then((isMatch) => {
                                            logger.debug("isMatch", isMatch) // logs true/false ?
                                            if (isMatch) {
                                                entities.push(instance);
                                            }
                                        })
                                        .catch((err) => {
                                            logger.error("Failed to match entity: ", err)
                                        })
                                })
                                    .catch((err) => {
                                        logger.error("Failed to read entity: ", err)
                                    })
                            });
                            /*
                            Promise.resolve(matches)
                                .then(() => {
                                    setTimeout(() => {
                                        logger.debug("Match count:", entities.length);
                                        logger.debug("Matching entities:", entities) // logs result of entities
                                    }, 5000)
                                    //resolve(entities)
                                })
                            */
                            Promise.resolve(matches)
                                .then(() => {
                                    logger.debug("Match count:", entities.length);
                                    logger.debug("Matching entities:", entities) // logs [undefined, undefined ....]
                                    resolve(entities)
                                })

                        })
                        .catch((err) => {
                            console.error("Failed to parse query: ", err)
                        });
            })
    })
}`

格式有点乱。我很确定为什么。 如果您需要更多信息,请告诉我。

最佳答案

let matches = response.keys.map((key) => {
    // the mapping function:
    readEntity(key).then((instance) => {

映射函数似乎没有返回值。这将创建一个包含未定义元素的映射数组。

let matches = response.keys.map((key) => {
    return readEntity(key).then((instance) => {
      // mapping function

可以通过使用读取和处理实体的 promise 填充匹配来更好地工作。等待 promise 完成可以使用 Promise.all 来完成,所以

 Promise.all(matches).then( ... process the entities array

更有可能工作
Promise.resolve(matches).then( ... process entities

除非 matches 是一个未决的 promise ,否则它不会等待任何异步的事情——但如果是这样,您就不需要在调用 then 之前解决它。

请注意代码缩进令人困惑,因此请检查控制台是否有错误,以查看 matches 在处理时是否在范围内 - 我无法看到它在范围内。

关于javascript - 异步 promise 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46522352/

相关文章:

javascript - Async/Await 区分拒绝和错误

javascript - 如何正确编码/调试复杂的 bool 条件

javascript - 从单个文件在站点的特定页面上执行自定义 JavaScript

multithreading - future 与线程 : Which is better for working with channels in core. 异步?

mysql - Node.js 使用异步方式运行 MySQL 查询

javascript - 使用 Async 和 Await 解析多个方法后运行代码

javascript - 使用 ng-table Angular 计算列的总和

javascript - Jquery 排序功能不适用于 Chrome 浏览器

Java:使用异步编程优化应用程序

javascript - 返回 promise 方式的差异