递归,节点js和异步调用

时间:2015-05-22 17:16:19

标签: javascript node.js recursion promise q

我试图将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
        });
    });
}

2 个答案:

答案 0 :(得分:1)

这是因为saveOverriddenPlaces没有返回值,因此它不会传递给函数2中的.then语句。 "解决方案"的目的是确保saveOverridenPlaces返回一个Promise,它使用您希望传递给成功的值来调用resolve。

答案 1 :(得分:0)

问题在于行

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

你的saveOverriddenPlaces函数没有(总是)返回一个promise或一个值。如果函数是异步的,那么必须始终返回一个promise。

您可以通过在条件语句中return次调用之前添加groupSettingsDAO.…().then(…)来轻松完成此操作 - then does return如果您returnthen,则可以完全符合您的承诺/从其回调中贬低。

但是,您应该尽量避免使用deferred antipattern。对于您的基本情况,请使用Q function创建履行承诺,其他所有内容只需链接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); }); } 次调用 - 无需延期。

protein(annexin,[phe,leu,gly]).
code(phe, ['UUU','UUC']).
code(leu, ['UUA','UUG']).
code(gly, ['GGC','GGU']).

rna(X, R) :- protein(X, LC), maplist(code_p, LC, R).
code_p(C, R) :- code(C, L), member(R, L).