【问题标题】:Recursion, Node js and Asynchronous calls递归、Node js 和异步调用
【发布时间】:2015-08-04 19:33:36
【问题描述】:

我正在尝试将 savePlaces 数组作为最终输出,以便可以在响应中返回它。但是我在function2()中获得了未定义的成功。 为什么我没有按预期获得 savePlaces。请提供解决方案....

var saveOverriddenPlaces = function(index, savePlaces) {
    var groupSettingsDAO = new GroupSettingsDAO();
    var deferred = q.defer();
    if (index == savePlaces.length) {
        console.log("-----------------------------deferred--------------------------------", deferred);
        console.log("LAST RETURN -----------------------------" + savePlaces + "----------------------------------------------------", index);
        deferred.resolve(savePlaces);
        return deferred.promise;
    }
    var placeInfo = {
        "id": savePlaces[index].id,
        "groupurl": savePlaces[index].groupurl,
        "sla": savePlaces[index].sla
    };
    if (savePlaces[index]._id) {
        placeInfo._id = savePlaces[index]._id;
        //update the overriden places in the database
        groupSettingsDAO.updateOverriddenPlace(placeInfo)
            //updates the overriden place and sends result in response when successful else logs error
            .then(
                //success
                function(success) {
                    console.log("recursion ============" + index + "=======================");
                    deferred.resolve(saveOverriddenPlaces(++index, savePlaces));

                    return deferred.promise;
                },
                //failure
                function(error) {
                    console.log("PLACES     ERROR ===================================", error);
                });
        // placesWithID.push(value);
    }
    //WITHOUT ids
    else {
        placeInfo._id = guid();
        savePlaces[index]._id = placeInfo._id;
        groupSettingsDAO.saveOverriddenPlace(placeInfo)
            // saves the overridden place and sends the results in response if successful else logs the error
            .then(
                //success
                function(success) {
                    console.log("recursion ============" + index + "=======================");
                    deferred.resolve(saveOverriddenPlaces(++index, savePlaces));
                },
                //failure
                function(error) {
                    console.log("PLACES     ERROR ===================================", error);

                });
    }
}
function2(req, res) {
    saveOverriddenPlaces(0, req.savePlaces).then(function(success) {
        //getting success as undefined 
        res.send({
            "result": success
        });
    });
}

【问题讨论】:

  • 我正在使用 Q 库,groupSettingsDAO 是一个 dao 对象,它有方法 updateOverriddenPlace() 返回一个承诺。

标签: javascript node.js recursion promise q


【解决方案1】:

问题是在行

deferred.resolve(saveOverriddenPlaces(++index, savePlaces));

您的saveOverriddenPlaces 函数不会(总是)返回一个承诺或一个值。如果函数是异步的,它必须始终返回一个 Promise。

您可以通过在条件语句中的 groupSettingsDAO.…().then(…) 调用之前添加 return 轻松做到这一点 - 如果您 return 来自其回调的值/prmise,then does return 正是您想要的承诺。

但是,您应该尽量避免使用deferred antipattern。对于您的基本情况,使用 Q function 创建一个已履行的承诺,对于其他所有内容,只需链接 then 调用 - 无需延迟。

function saveOverriddenPlaces(index, savePlaces) {
    if (index == savePlaces.length) {
        console.log("LAST RETURN -" + savePlaces + "-", index);
        return Q(savePlaces);
    }
    var groupSettingsDAO = new GroupSettingsDAO();
    var placeInfo = {
        "id": savePlaces[index].id,
        "groupurl": savePlaces[index].groupurl,
        "sla": savePlaces[index].sla
    };
    var promise;
    if (savePlaces[index]._id) {
        placeInfo._id = savePlaces[index]._id;
        promise = groupSettingsDAO.updateOverriddenPlace(placeInfo); //update the overriden places in the database
        // placesWithID.push(value);
    } else { // WITHOUT ids
        placeInfo._id = guid();
        savePlaces[index]._id = placeInfo._id;
        promise = groupSettingsDAO.saveOverriddenPlace(placeInfo) // saves the overridden place
    }
    return promise.then(function(success) {
//  ^^^^^^
        console.log("recursion =" + index + "=" + success);
        return saveOverriddenPlaces(++index, savePlaces));
//      ^^^^^^
    });
}
function2(req, res) {
    saveOverriddenPlaces(0, req.savePlaces).then(function(success) {
        //getting success as undefined 
        res.send({
            "result": success
        });
    }, function(error) {
        console.log("PLACES ERROR =", error);
    });
}

【讨论】:

  • 感谢您回复伯吉。我终于明白我在哪里犯了错误。:-)
  • @user3209475:很高兴听到!那么请accept the answer
【解决方案2】:

这是因为saveOverriddenPlaces 没有返回值,因此它没有传递给函数二中的.then 语句。 “解决方案”是确保 saveOverridenPlaces 返回一个 Promise,该 Promise 调用 resolve 并带有您想要传递给成功的值。

【讨论】:

  • 感谢您的回复,但我也明白 saveOverriddenPlaces 没有返回承诺。问题是我无法弄清楚我该怎么做。当我尝试在最后一个索引值上返回具有更新值的数组时。我阅读了其他关于使用 promises 使用 node.js 进行递归的文章,但无法解决这个问题。
  • 明白问题了。
猜你喜欢
  • 1970-01-01
  • 2016-07-25
  • 2014-12-18
  • 2018-10-27
  • 2014-05-21
  • 2016-02-07
  • 2017-10-28
  • 2018-01-30
  • 2016-09-21
相关资源
最近更新 更多