gpt4 book ai didi

javascript - 递归、Node js 和异步调用

转载 作者:行者123 更新时间:2023-12-03 10:04:53 27 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - 递归、Node js 和异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402433/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com