初学者问题:(可选)承诺结合箭头/访问 result/error 值

Beginner Question: (optional) promises in combination with arrows / accessing result/error values

这是一个用猫鼬为我的 mongoDB 创建对象的简单函数:

Item.create({ name: req.body.newItem }, function (err, res) {
  if (err) return handleError(err);
  // saved!
});

现在,我正在学习承诺的概念。由于 create API returns 是一个可选的承诺,为了学习目的和可读性,我想使用它。

我的做法是这样的:

let newItem = Item.create(
        {name: req.body.newItem}).then(() => console.log("Success"), () => console.log("Error!"));

这确实有效。但我在这里欺骗自己。我真正想要的是具有与上面相同的代码,这意味着使用 (err, small) 并将其合并到我的 .then().
我知道每个承诺都有一个解决或拒绝的状态,并且可以使用这些。我不知道如何在这里执行此操作的概念,因为 .then((resolve, reject) 是不允许的

编辑:
我刚试过这个:

let newItem = Item.create(
        {name: req.body.newItem}).then(result => console.log("Success: " + result), (error) => console.log("Error: " + error));  

这似乎有效。我想我当时还没有完全掌握箭头的概念。我认为相当于

function(a, b){
if(a){
do Something()
}else{ //so it has to be b
do otherThing()
}

将是 .then(a,b) => doSomething(),do otherThing()

在使用 Promises 时,您有(不仅)两种在大多数情况下都需要的方法:

  • then() - 它在 Promise 解析时接收回调函数,在 Promise 拒绝时接收回调函数。如果您省略第二个回调并且 Promise 拒绝,将重新抛出错误并需要进一步处理
  • catch() - 当 Promise 拒绝时接收回调函数

在您的情况下,.create() Promise 可能会实现或被拒绝(这些并不是 Promise 可以拥有的所有状态)。要处理这两种情况,您可以像这样链接 .then().catch()

Item.create({name: req.body.newItem })
  .then((result) => {
    console.log('resolved', result);
  })
  .catch((error) => {
     handleError(error);
  })

或者像这样:

Item.create({name: req.body.newItem })
  .then(
      (result) => {
          console.log('resolved', result);
      },
      (error) => {
         handleError(error);
      }
  );

两种方法是等效的。

一般来说,Promises 处理看起来像这样:

somethingReturnsPromise()
    .then((result) => {
        // handle result
    })
    .catch((error) => {
        // handle error
    });

但这不仅仅是 Promises 的全部。我建议您阅读更多有关它们的信息,例如 this article.

其他答案很好地描述了 promise 的工作原理。但是如果你需要这样做:

What I actually want is to have the same code as above, that means using the (err, small) and incorporating that into my .then()

您可以简单地使用 promise 中的空错误参数调用该函数:

const existingFunction = (err, small) => { /* Do stuff */ }

Item.create({name: req.body.newItem })
  .then(newItem => {
    existingFunction(null, newItem)
  })
  .catch(err => {
     existingFunction(err)
  })