我正在尝试通过递归方法(通过Mongoose)保存多个文档。

我创建了一个Promise,它解析了方法admin_save_choices()来保存文档的Array,并在保存文档或错误消息后最终返回了ArrayObjects。当文档保存在回调中时,它会递归调用自身(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(回调。

它在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));
});


编辑:为防反模式着想:)

09-30 13:02
查看更多