简体   繁体   English

然后捕获和然后捕获承诺之间的差异

[英]Difference between then catch and a then catch inside a promise

What is the difference between these two? 这两者有什么区别? Is one faster than the other? 一个比另一个快吗? Both seem to work. 两者似乎都有效。 Someone please explain 有人请解释一下

One with no promise: 一个没有承诺:

client.query(query1)

.then(data => {
   callback(null, {
       statusCode: 200,
       body: JSON.stringify(data)
   });                    
.catch(err => {
   callback(null, {
       statusCode: 500,
       body: JSON.stringify(err)
   }); 
});

Other with a promise: 其他承诺:

return new Promise((resolve, reject) => {

 client.query(query2)

    .then(data => {
      resolve({statusCode:200, body: JSON.stringify(data)}); 
    })
    .catch(err => {
       reject(err);
    });

});

Lets start with what these 2 code snippets have in common. 让我们从这两个代码片段的共同点开始。 They both invoke some client.query() function which we know nothing about, however we can guess it returns a Promise instance. 它们都调用了一些我们一无所知的client.query()函数,但我们可以猜测它会返回一个Promise实例。 I will assume this for the rest of the answer. 我会在接下来的答案中假设这一点。

What is the difference between these two? 这两者有什么区别?

The difference between the two is how they return the result from an asynchronous operation. 两者之间的区别在于它们如何从异步操作返回结果。 While the first one uses a callback, the latter uses a Promise , which is more than just a callback. 虽然第一个使用回调,但后者使用Promise ,它不仅仅是一个回调。 It provides state (pending / fulfilled / rejected) and supports chaining . 它提供状态(待处理/履行/拒绝)并支持链接 You could, of course, chain callbacks too, but it will inevitably end up in callback hell . 当然,你也可以链接回调,但它不可避免地会在回调地狱中结束。 In the second snippet you could have returned the original promise, but in my opinion wrapping it in your own promise is probably a good thing, because you're abstracting away the results returned the original promise. 在第二个片段中你可以返回原来的承诺,但在我看来,将它包装在你自己的承诺中可能是一件好事,因为你抽象掉了原来的承诺。

Is one faster than the other? 一个比另一个快吗?

I wouldn't worry about this matter. 我不担心这件事。 In asynchronous programming it's usually waiting for the result of aynchronous operation that takes the most time. 在异步编程中,它通常等待花费最多时间的异步操作的结果。 The mechanism how you report the result of such operation to caller is irrelevant from performance point of view. 从性能的角度来看,如何向调用者报告此类操作的结果的机制是无关紧要的。 What however matters in asynchronous programming is code readability and maintainability, which might not be optimal even if you use promises. 在异步编程中重要的是代码可读性和可维护性,即使使用promises也可能不是最佳的。 And that leads us to async functions introduced in ES2017. 这导致我们在ES2017中引入了异步功能

I'm not encouraging you to use async function straight away. 我不鼓励你马上使用异步功能。 Just be aware of it, study it and use when appropriate. 只要注意它,研究它并在适当的时候使用。

the short answer is then always returns a Promise . 简短的回答then总是返回一个Promise when any promise is rejected within the chain it will execute the first catch. 当任何承诺在链中被拒绝时,它将执行第一个捕获。 (throwing an error within then will return a rejected promise). (内抛出一个错误then会返回一个拒绝承诺)。

then will return a promise of the returned value if it's not a promise and return a rejected promise if an error was thrown. then ,如果它不是一个promise,则返回一个返回值的promise,如果抛出一个错误,则返回一个被拒绝的promise。

so the first one is also returning a Promise of undefined , and there's no difference in performance, 所以第一个也是返回undefinedPromise ,并且性能没有差别,

const p1 = Promise.resolve('this will resolve');

p1.then((x) => Promise.resolve('You know: ' + x)).then(str => console.log(str));
p1.then((x) => Promise.reject('this will not resolve')).then(x => console.log('this will never execute')).catch(e => console.log('told you : ' + e));

p1.then((x) => 'You know: ' + x).then(str => console.log(str));
p1.then((x) => { throw 'this will not resolve' }).then(x => console.log('this will never execute')).catch(e => console.log('told you : ' + e));

Both of these methods do the same thing within then. 这两种方法都在那时做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM