可实现与承诺之间有什么区别

I was happily doing some backend coding and at the part where I had to write a mongoose query to return a list of items, I got confused at whether I should chain .exec() or .then() behind the myModel.find() method. So I ended up searching their docs in an attempt to (try to) figure out which is the one I should use. Here’s a paragraph from their documentation:

我愉快地做一些后台编码,并在那里我不得不写一个猫鼬的查询返回的项目列表中的一部分,我在糊涂了是否我应该链.exec().then()后面myModel.find()方法。 因此,我最终搜索了他们的文档,以尝试(尝试)找出应该使用的文档。 这是他们文档中的一段:

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .exec() function.

猫鼬查询不是承诺。 为了方便起见.then()它们具有.then()函数用于co和async / await。 如果您需要完整的承诺,请使用.exec()函数。

At that moment I was like…what’s a “fully-fledged promise”? What does it even mean in this context?

那一刻,我就像……什么是“成熟的诺言”? 在这种情况下,这甚至意味着什么?

And the journey of trying to figure out what that phrase means got me to this link and I found out that what they meant was that Mongoose queries are thenables and not promises. According to that link,

试图弄清楚该词组的含义的过程将我带到了该链接,我发现它们的含义是猫鼬查询是可以实现的,而不是承诺。 根据该链接,

“promise” is an object or function with a then method whose behavior conforms to this specification.

“承诺”是具有then方法的对象或函数,其行为符合此规范。

“thenable” is an object or function that defines a then method.

“ thenable”是定义then方法的对象或函数。

Okay so naturally, the question now is — what does “whose behavior conforms to this specification” mean? To answer this question, let us take a closer look at what a “real” A.K.A “fully-fledged promise” means (and then we’ll look at why it’s different from thenables after that).

那么自然就可以了,现在的问题是:“其行为符合该规范”是什么意思? 为了回答这个问题,让我们仔细研究一下“真正的” AKA“完全承诺”的含义(然后,我们将研究为什么它与随后的可实现物不同)。

Traditionally, the then() method returns a Promise. It takes up to two arguments: callback functions for the success (onFulfilled) and failure (onRejected) cases of the Promise. And a promise can take up three states — pending, fulfilled, or rejected. Thenables, however, does not work this way. We won’t be able to pass in two callback functions like how we did with a “fully-fledged promise”. To illustrate this with some code:

传统上, then()方法返回Promise 。 它包含两个参数: Promise的成功(onFulfilled)和失败(onRejected)案例的回调函数。 一个承诺可以包含三个状态-未决,已实现或已拒绝。 然而,罐头无法通过这种方式工作。 我们将无法传递两个回调函数,例如我们如何使用“完全承诺”。 为了用一些代码来说明这一点:

UserModel.find().exec((err, users) => {  if (err) return res.status(400).send(err);  res.status(200).json({    success: true,    users,  });});

This works fine because the two callback functions we passed in for the success and failure cases are called err (failure case) and the success/result case is called users.

这很好用,因为我们为成功案例和失败案例传入的两个回调函数称为err(失败案例),成功/结果案例称为用户。

Note that all callbacks in Mongoose use the pattern: callback(error, result) — this is different from the order of the callback functions specified in the MDN web docs. Now, if we run the same piece of code but replace exec() with then() like so:

请注意,Mongoose中的所有回调都使用以下模式: callback(error, result) -这与MDN Web文档中指定的回调函数的顺序不同。 现在,如果我们运行同一段代码,但是用then()替换exec() ,如下所示:

UserModel.find().then((err, users) => {  if (err) return res.status(400).send(err);  res.status(200).json({    success: true,    users,  });});

This returns a 400 Bad Request Status. This is because Mongoose queries are not “fully-fledged promises” and so we cannot chain a .then() behind a query and then expect it to act like a real promise. However, if we really want to use .then() instead of .exec(), we can still chain a .catch() after the .then() for error handling:

这将返回400错误请求状态。 这是因为猫鼬查询不是“完整的承诺”,因此我们不能在查询后链接.then() ,然后期望它像真正的承诺一样工作。 但是,如果我们真的想用.then()代替.exec()我们仍然可以链接一个.catch().then()用于错误处理:

// {_id:1} is included to make this fail
UserModel.find({ _id: 1 }) .then((users) => { res.status(200).json({ success: true, users, }); }) .catch((err) => { res.status(400).send(err); });

Including the {_id:1} will force it to return a 400 Bad Request. If I remove it, users get returned fine.

包含{_id:1}将强制其返回400 Bad Request。 如果我删除它,用户会被罚款。

Lastly, remember that all promises are thenables, but not all thenables are promises.

最后,请记住,所有的承诺都是可实现的,但并非所有的可实现都是可实现的。

Really hope this helps someone! Thank you for reading this :)

真希望这对某人有所帮助! 谢谢您阅读此篇 :)

翻译自: https://medium.com/javascript-in-plain-english/whats-the-difference-between-a-thenable-and-a-promise-74d697bc9c79

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值