在 for 循环中解析 Cloud Code Promise

Parse Cloud Code Promises in a for loop

如标题所述,我在 Parse 中遇到 Promises 问题。

我正在努力首先了解 Promises 本身是如何工作的,尤其是在 Parse 中。

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

我想做的是抓取一个网站,然后从 table 创建 objects(这是有效的)

麻烦来了,我是不是 运行 对结果进行 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 创建 objects 并将它们添加到数组的函数:

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;
};

The Get Dam Object 代码:

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 方面还是个新手,我最近才开始学习它以便使用我的服务器代码。

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 是一个异步函数,它将 return 一个在迭代完成后解析为数组的 Promise。在另一个异步函数中使用 await getDamObjects(或使用 .then