将承诺嵌入承诺中

时间:2018-04-06 11:25:07

标签: javascript node.js promise sequelize.js

我对node.jsPromise功能都不熟悉,如果这个问题真的很愚蠢,请原谅我。

我正在尝试在Parent调用中创建一个子Promise调用forEach子项(如果这有意义的话)。

这是我的代码:

        return new Promise(function(resolve, reject) {
            var authorMapArray = new Array
            db.sequelize.query(authorQuery, {
                replacements: queryParams
            }).spread(function(authorSitemap) {
                authorSitemap.forEach(function(obj) {
                    /*
                    return new Promise (function(resolve, reject){
                        var thisQuery = photoQuery + ' AND author = ' + obj.id.toString();
                        db.sequelize.query(thisQuery, {
                            queryParams
                        }).spread(function(authorImages) {
                            var authorImageArray = new Array;
                            authorImages.forEach(function(obj) {
                                var imgLink = { url: imgHost + obj.img_id + '.jpg', title : img_tags }
                                authorImageArray.push(imgLink);
                            })
                        });
                        resolve(authorImageArray);
                    });
                    */
                    var authorLink = { url: 'author/' + obj.id, /*img: authorImageArray,*/ changefreq: 'weekly', priority: 0.6, lastmodrealtime: true }
                    siteMapArray.push(authorLink);
                });
                resolve(siteMapArray);

                //and finally create it
                createSiteMap(siteMapArray);
            });
        })

你会注意到,中间的部分被注释掉了。当我运行这样的代码时,我得到了我期望的结果,即authorLink添加到站点地图中。当我取消注释代码时(为了在站点地图中包含与作者相关联的图像),甚至不添加作者链接。

如何将作者的图像包含在他们的记录中?

修改

这是更完整的代码:

function createSiteMap(myURLs) {
    var rows = 10000;
    var totalMaps = Math.trunc(myURLs.length/rows)+1;
    var today = new Date();
    var mySitemaps = new Array;
    for (var i=1; i<totalMaps+1; i++) {
        var filename = "public/sitemap-" + i.toString() + ".xml";
        var sitemap = sm.createSitemap({
            hostname: hostname,
            cacheTime: 600000,  //600 sec (10 min) cache purge period 
            urls: myURLs.slice((i-1)*rows,i*rows)
            });
        fs.writeFileSync(filename, sitemap.toString());
        mySitemaps.push(filename);
    }

    // this needs to create sitemap tags not url tags
    var smi = sm.buildSitemapIndex({
        urls: mySitemaps
        });
    fs.writeFileSync("public/sitemap.xml", smi.toString());

    process.exit();
}

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

function getPhotos() {
    return new Promise(function(resolve, reject) {
        var siteMapArray = new Array()        
        var tags = new Array()
        siteMapArray.push ({ url: '/' , changefreq: 'weekly', priority: 0.8, lastmodrealtime: true, lastmodfile: 'views/home.hbs' },)
        db.sequelize.query(photoQuery, {
            replacements: queryParams
        }).spread(function(makeSiteMap) {
            makeSiteMap.forEach(function(obj) {
                // images for sitemap
                var img_tags = obj.tags.replace(/,/g , " ");
                var imgLink = { url: imgHost + obj.img_id + '.jpg', title : img_tags }
                var siteLink = { url: 'photo/' + obj.img_id, img: imgLink, changefreq: 'weekly', priority: 0.6, lastmodrealtime: true }
                siteMapArray.push(siteLink);
                obj.tags = obj.tags.split(',').map(function(e) {
                    return e.trim().split(' ').join('+');
                });
                for (var tag in obj.tags) {
                    tags.push(obj.tags[tag])
                }
            });

            resolve (siteMapArray);

            //tags for sitemap
            var uniqueTags = uniq(tags);
            for (var tag in uniqueTags) {
                var siteLink = { url: '/search/' + uniqueTags[tag], changefreq: 'weekly', priority: 0.8, lastmodrealtime: true }
                siteMapArray.push (siteLink);
            }

            //now author tags
            return new Promise(function(resolve, reject) {
                var authorMapArray = new Array
                db.sequelize.query(authorQuery, {
                    replacements: queryParams
                }).spread(function(authorSitemap) {
                    authorSitemap.forEach(function(obj) {
                        /*
                        return new Promise (function(resolve, reject){
                            var thisQuery = photoQuery + ' AND author = ' + obj.id.toString();
                            db.sequelize.query(thisQuery, {
                                queryParams
                            }).spread(function(authorImages) {
                                var authorImageArray = new Array;
                                authorImages.forEach(function(obj) {
                                    var imgLink = { url: imgHost + obj.img_id + '.jpg', title : img_tags }
                                    authorImageArray.push(imgLink);
                                })
                            });
                            resolve(authorImageArray);
                        });
                        */
                        var authorLink = { url: 'author/' + obj.id, /*img: authorImageArray,*/ changefreq: 'weekly', priority: 0.6, lastmodrealtime: true }
                        siteMapArray.push(authorLink);
                    });
                    resolve(siteMapArray);

                    //and finally create it
                    createSiteMap(siteMapArray);
                });
            })

        });
    });
};

getPhotos();

2 个答案:

答案 0 :(得分:3)

好的,我们假设你想要这样的东西:

function getSiteMapArray() {
  // return a promise that resolves to the siteMapArray
}

第一步是在不使用new Promise()的情况下重写它 - 你不应该经常使用这个,因为大多数使用promises的工作只是链接.then()调用,这些调用更具可读性。

请注意,.spread()只是一个带有糖的.then()。糖不是标准的Promise语法,而是来自bluebird sequelize建议使用的插件。对于使用带有2个值的数组解析的promise,它们是等效的:

something.then(resultArray => ...);
something.spread((resultItem1, resultItem2) => ...);

(我将使用arrow functions,是吗?)

所以第一步是在我们开始合并您的评论中的代码之前,按照承诺摆脱new Promise()

function getSiteMapArray() {
  var authorMapArray = new Array();
  return db.sequelize
    .query(authorQuery, {
      replacements: queryParams
    })
    .spread(authorSitemap => {
      authorSitemap.forEach(function(obj) {
        var authorLink = {
          url: "author/" + obj.id,
          /*img: authorImageArray,*/
          changefreq: "weekly",
          priority: 0.6,
          lastmodrealtime: true
        };
        siteMapArray.push(authorLink);
      });
      return siteMapArray;
    });
}

够简单吗?

  • 我们使用.query()来获得结果承诺,
  • 然后我们使用.then().spread()传递处理结果的回调,
  • spread()会返回一个新的承诺,在我们完成所有操作后会解决,而此承诺是getSiteMapArray()的结果。它将使用return siteMapArray
  • 中的值来解决

我们可以使用map()而不是forEach进一步简化,只要您想要转换数组中的每个元素,建议使用function getSiteMapArray() { return db.sequelize .query(authorQuery, { replacements: queryParams }) .spread(authorSitemap => { return authorSitemap.map(obj => ({ url: "author/" + obj.id, /*img: authorImageArray,*/ changefreq: "weekly", priority: 0.6, lastmodrealtime: true })); }); }

function getSiteMapArray() {
  return db.sequelize
    .query(authorQuery, {
      replacements: queryParams
    })
    .spread(authorSitemap => {
      return authorSitemap.map(getAuthorDescription);
    });
}

function getAuthorDescription(obj) {
  return {
    url: "author/" + obj.id,
    /*img: authorImageArray,*/
    changefreq: "weekly",
    priority: 0.6,
    lastmodrealtime: true
  };
}

这就是容易的部分,现在我们如何在这里合并authorImage查询?

让我先提取一个帮手:

getAuthorDescription

现在function getAuthorDescription(obj) { var thisQuery = photoQuery + " AND author = " + obj.id.toString(); return db.sequelize .query(thisQuery, { queryParams }) .spread(function(authorImages) { var authorImageArray = new Array(); authorImages.forEach(function(obj) { var imgLink = { url: imgHost + obj.img_id + ".jpg", title: img_tags }; authorImageArray.push(imgLink); }); return { url: "author/" + obj.id, img: authorImageArray, changefreq: "weekly", priority: 0.6, lastmodrealtime: true }; }); } 是同步的,但我们希望它自己进行查询,所以让我们把它重写为异步,这样它也会返回一个承诺!

.map()

使用function getSiteMapArray() { return db.sequelize .query(authorQuery, { replacements: queryParams }) .spread(authorSitemap => { return authorSitemap.map(getAuthorDescription); // !!! }); } 的另一个好例子,但我会留给你一个。

返回原始代码:

getAuthorDescription

哇,现在我们遇到了麻烦 - getSiteMapArray返回了一个承诺,所以我们用一个承诺列表来解析getAuthorDescription,而不是值列表!

我们需要一种方法来等待从function getSiteMapArray() { return db.sequelize .query(authorQuery, { replacements: queryParams }) .spread(authorSitemap => { return Promise.all(authorSitemap.map(getAuthorDescription)); }); } 返回的每个承诺完成,并获得所有这些承诺的收集结果数组。这种方式称为Promise.all

所以代码变成:

abstract class AbstractSuperClass {
  protected Entity entity;
  protected abstract Action action; // all subclasses must define this on their own

  public AbstractSuperClass(Entity entity) {
    this.entity = entity;
  }

  public void operate() {
    this.action.doVoidMethod();
  }
}

public class SubClass extends AbstractSuperClass {
  public SubClass(Entity entity) {
    super(entity);
    this.action = new Action(); // I define the "abstract" property
    // now I expect SubClass.operate() to do this.action.doVoidMethod();
  }
}

请告诉我这是否有帮助!

答案 1 :(得分:2)

您的实施中存在几个问题。我建议不要将[].foreach用于儿童承诺。为子承诺制作单独的方法,并使用promise.all为每个authorSitemap调用它。

以下是更新的示例实现。

return new Promise(function(resolve, reject) {
            var authorMapArray = new Array
            db.sequelize.query(authorQuery, {
                replacements: queryParams
            }).spread(function(authorSitemap) {

                return Promise.all(authorSitemap.map(GetAuthor))
                .then(function(authorImageArray){
                    var authorLink = { url: 'author/' + obj.id, img: authorImageArray, changefreq: 'weekly', priority: 0.6, lastmodrealtime: true }
                    siteMapArray.push(authorLink);
                    createSiteMap(siteMapArray);
                    resolve(siteMapArray);
                })
                .catch(function(error){
                    reject(error);
                })
            });
        })

function GetAuthor(obj) {
    return new Promise(function(reject,resolve){
        var thisQuery = photoQuery + ' AND author = ' + obj.id.toString();
        db.sequelize.query(thisQuery, { queryParams})
                    .spread(function(authorImages) {
                            var authorImageArray = new Array;
                            authorImages.forEach(function(obj) {
                                var imgLink = { url: imgHost + obj.img_id + '.jpg', title : img_tags }
                                authorImageArray.push(imgLink);
                            })
                            resolve(authorImageArray);
                        });
    })
}