解析for循环中的云代码承诺

时间:2018-04-14 01:16:03

标签: javascript parse-platform promise parse-server cloud-code

正如标题所述,我在Parse中遇到了Promise的问题。

我努力首先明白Promise本身是如何运作的,特别是在Parse中。

我已经坚持了大约三个星期,而我最接近解决方案的是返回一个空数组。

我想要做的是刮一个网站,然后从表中创建对象(这是有效的)

如果出现问题,我是否在结果上运行for循环并查询每个Dam名称以从数据库中获取结果objectid。

这是我的代码:

var c = new Crawler({
    maxConnections: 10,
    // This will be called for each crawled page
    callback: function(err, res, done) {
        if (err) {
            console.log(err);
        } else {
            var $ = res.$;
            // $ is Cheerio by default
            //a lean implementation of core jQuery designed specifically for the server
            console.log($("title").text());
        }
        done();
    }
});

从Dom创建对象并将它们添加到数组中的函数:

function getDamObjects(Dom) {
    var dom = Dom;
    var LevelObjects = [];

    for (i = 1; i < dom.length - 1; i++) {
        var TableRow = dom.eq(i);

        var NameString = TableRow.children().eq(0).text();
        var RiverString = TableRow.children().eq(1).text();
        var FSCString = TableRow.children().eq(4).text();
        var ThisWeekString = TableRow.children().eq(5).text();
        var LastWeekString = TableRow.children().eq(6).text();
        var LastYearString = TableRow.children().eq(7).text();

        NameString = NameString.replace('#', '');
        NameString = NameString.replace('$', '');
        NameString = NameString.replace('&', '');
        NameString = NameString.replace('@', '');

        ThisWeekString = ThisWeekString.replace('#', '');
        ThisWeekString = ThisWeekString.replace('$', '');
        ThisWeekString = ThisWeekString.replace('&', '');
        ThisWeekString = ThisWeekString.replace('@', '');

        LastWeekString = LastWeekString.replace('#', '');
        LastWeekString = LastWeekString.replace('$', '');
        LastWeekString = LastWeekString.replace('&', '');
        LastWeekString = LastWeekString.replace('@', '');

        LastYearString = LastYearString.replace('#', '');
        LastYearString = LastYearString.replace('$', '');
        LastYearString = LastYearString.replace('&', '');
        LastYearString = LastYearString.replace('@', '');

        var level = {};
        /*
        getDamObject(NameString).then(function(DamObject){
        let DamID = DamObject.id;
        */
        level['Dam'] = NameString; //DamID;
        level['ThisWeek'] = ThisWeekString;
        level['LastWeek'] = LastWeekString;
        level['LastYear'] = LastYearString;

        LevelObjects.push(level);
    };
    return LevelObjects;
};

获取水坝目标代码:

function getDamObject(Dam) {
    var promise = new Parse.Promise();

    var query = new Parse.Query("DayZeroDams");
    query.equalTo("Name", Dam);
    query.first().then(function(DamObject) {
        promise.resolve(DamObject);
    }, function(error) {
        promise.reject(error);
    });

    return promise;
}

所谓的云代码:

Parse.Cloud.define('jsdom', function(request, response) {
    c.queue([{
        uri: 'xxxxxx',
        // The global callback won't be called
        callback: function(err, res, done) {
            if (err) {
                response.error(err);
            } else {
                var $ = res.$;
                var ResultsArray = [];
                var dom = res.$('#mainContent_tw').children('tr');
                return Parse.Promise.as().then(function() {
                    var promise = Parse.Promise.as();
                    var LevelObjects = getDamObjects(dom);
                    _.each(LevelObjects, function(DamLevel) {
                        promise = promise.then(function() {
                            var Name = DamLevel["Dam"];
                            var query = new Parse.Query("DayZeroDams");
                            query.equalTo("Name", Name);
                            return query.first().then(function(result) {
                                let damID = result.id;
                                ResultsArray.push(damID);
                                return Parse.Promise.as();
                            }, function(error) {
                                response.error(error);
                            });
                        });
                    });
                    return promise;
                }).then(function() {
                    response.success(ResultsArray);
                }, function(error) {
                    response.error(error);
                });
                //response.success(LevelObjects);
            }
            done();
        }
    }]);
});

请注意我在Javascript方面相当新手,我最近才开始学习它以使用我的服务器代码。

1 个答案:

答案 0 :(得分:1)

getDamObjects转换为异步函数,然后await每行的结果,将其推送到数组:

function replaceSymbols(input) {
  return input.replace(/[#\$&@]/g, '');
}
async function getDamObjects(Dom) {
  const dom = Dom;
  const levelObjects = [];
  for (let i = 1; i < dom.length - 1; i++) {
    const children = dom.eq(i).children();

    const NameString = replaceSymbols(children.eq(0).text());
    const RiverString = children.eq(1).text();
    const FSCString = children.eq(4).text();
    const ThisWeek = replaceSymbols(children.eq(5).text());
    const LastWeek = replaceSymbols(children.eq(6).text());
    const LastYear = replaceSymbols(children.eq(7).text());

    const Dam = await getDamObject(NameString);
    levelObjects.push({
      Dam,
      ThisWeek,
      LastWeek,
      LastYear,
    });
  }
  return levelObjects;
}

请记住,现在getDamObjects是一个异步函数,它将返回一个Promise,一旦迭代完成,它就会解析为数组。在另一个异步函数(或使用await getDamObjects

中使用.then来使用它