在Node JS中实现了Bluebird嵌套循环的承诺

时间:2017-04-08 10:45:33

标签: javascript node.js bluebird

我在NodeJS中使用蓝鸟。我想做一个嵌套循环。像这样:

  var Promise = require('bluebird');

  funcs.getLatestVideos = function(job, done) {
              return Promise.try(function() {
                      return ProcessRules.getLatestVideos();
                  })
                  .then(function(object) {
                      return ({
                          'series': ProcessRules.getSeriesRules(),
                          'videos': object.videos
                      });
                  })
                  .then(function(inputs) {
                      return Promise.map(inputs.videos, function(video) {
                          return Promise.map(inputs.series, function(series) {
                              return Promise.map(series.rules, function(rule) {
                                  return ProcessRules.processRules(video, rule);
                              });
                          });
                      })
                  })
                  .then(function(result) {
                      W.debug("done");
                      console.log(JSON.stringify(result));
                      done();
                  })
                  .catch(function(err) {
                      done(err);
                      W.error("Error occurred ", err.message, err.stack);
                  });
   }

ProcessRules

     var Promise = require('bluebird');
     var rp = require('request-promise');
     var W = require('winston');
     var RuleEngine = require('node-rules');
     var _ = require('lodash');

          funcs.getSeriesRules = function() {
              return new Promise(function(resolve, reject) {
                  var options = {
                      method: "GET",
                      uri: API_URL,
                      // body: status,
                      json: true // Automatically stringifies the body to JSON
                  };

                  rp(options)
                      .then(function(result) {
                          resolve(result)
                      })
                      .catch(function(err) {
                          reject(err)
                      });
              });
          };

            funcs.processRules = function(fact, rule) {
                return new Promise(function(resolve, reject) {
                    var rules = [];
                    var value = new RegExp(rule.value, 'i');

                    switch (rule.type) {
                        case 'title':
                            rules = [{
                                "condition": function(R) {
                                    //  console.log(this.title.match(value));
                                    R.when(this.title.match(value) > -1);
                                },
                                "consequence": function(R) {
                                    this.result = false;
                                    this.video = R;
                                    R.stop();
                                }
                            }];
                            break;
                        case 'desc':
                            rules = [{
                                "condition": function(R) {
                                    //console.log(this.desc.match(value));
                                    R.when(this.desc.match(value) > -1);
                                },
                                "consequence": function(R) {
                                    this.result = false;
                                    this.video = R;
                                    R.stop();
                                }
                            }];
                            break;
                        case 'tag':
                            rules = [{
                                "condition": function(R) {
                                    //  console.log(this.tag.match(value));
                                    R.when(!_.some(this.tags, { 'text': rule.value}))
                                },
                                "consequence": function(R) {
                                    this.result = false;
                                    this.video = R;
                                    R.stop();
                                }
                            }];
                            break;
                        default:
                            break
                    };

                    //initialize the rule engine
                    const R = new RuleEngine(rules);

                    //Now pass the fact on to the rule engine for results
                    R.execute(fact, function(result) {
                        //console.log(result);
                        if (result.result) {
                            resolve(result._id)
                        }else{
                          resolve({})
                        }
                    });
                });

            };

它返回输出

  [[[{},{},"58e9d6816961c30367b5154c"],[{}],[],[],[]],[[{},{},"58e9d6816961c30367b5154d"],[{}],[],[],[]]]

但我期待以下输出:

 [58e9d6816961c30367b5154c,58e9d6816961c30367b5154d]

我看到了一些类似的问题,但没有从中得到确切的想法。

getLatestVideos功能无法完成的结果中,请帮我解决此问题。

请帮我用蓝鸟承诺实现嵌套的每个循环。

1 个答案:

答案 0 :(得分:1)

经过长时间的搜索,有多个问题和答案后,我得到了Flattening a Promise map的答案。

我不知道它的正确方法,但它为我工作。

            .then(function(inputs) {
                return Promise.map(inputs.videos, function(video) {
                    return Promise.map(inputs.series, function(series) {
                        return Promise.map(series.rules, function(rule) {
                            return ProcessRules.processRules(video, rule);
                        }).reduce(function(prev, cur) {
                            return cur ? prev.concat(cur) : [];
                        }, [])
                    }).reduce(function(prev, cur) {
                        return prev.concat(cur);
                    }, [])
                }).reduce(function(prev, cur) {
                    return prev.concat(cur);
                }, [])
            })

它返回[58e9d6816961c30367b5154c,58e9d6816961c30367b5154d]

谢谢大家。