[英]Node JS: Promise resolve value is “undefined”
我試圖通過遞歸方法(通過Mongoose
)保存多個文檔。
我創建了一個Promise
,它解決了方法admin_save_choices()
以保存文檔Array
,並在保存文檔或錯誤消息后最終返回Objects
Array
。 當文檔保存在回調中時,它會遞歸調用自身( admin_save_choices()
),直到存在Array
元素為止。
這是Promise
-
let choices_object_array_promise = new Promise(function(resolve, reject) {
let choices_object_array = admin_save_choices(choices, timestamp);
resolve(choices_object_array);
});
choices_object_array_promise.then(function(result){
console.log(result);
res.status(200);
res.json('success');
}).catch(function(error) {
res.status(400);
res.json('error');
});
這是方法-
var admin_save_choices = function(choices, timestamp) {
let choices_object_array = [];
let choice = choices.shift();
if (typeof choice === "undefined")
return choices_object_array;
let choice_information = {
choice: choice,
created_time: timestamp
};
let save_choice_promise = choiceModel.save_choice(choice_information);
save_choice_promise.then(function(choice_result_object) {
choices_object_array.push(choice_result_object);
admin_save_choices(choices, timestamp);
}).catch(function(error) {
return 'error';
});
}
所有文檔都保存成功,除非我不知道結果返回到choices_object_array_promise.then(
回調。
在console.log(result)
顯示undefined
console.log(result)
提前致謝。
這是因為admin_save_choices
不返回任何內容。
我猜您正在嘗試返回admin數組,也許這就是您想要執行的操作:
// inside admin_save_choices
return save_choice_promise
.then(function(choice_result_object) {
choices_object_array.push(choice_result_object);
return admin_save_choices(choices, timestamp);
}).catch(function(error) {
return error;
});
}
let choices_object_array_fn = new Promise(function(resolve) {
resolve(admin_save_choices(choices, timestamp));
});
編輯:為防反模式着想:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.