Bluebird.JS承诺:新Promise(函数(解析,拒绝){})vs Promise.try(function(){}) [英] Bluebird.JS Promise: new Promise(function (resolve, reject){}) vs Promise.try(function(){})

查看:120
本文介绍了Bluebird.JS承诺:新Promise(函数(解析,拒绝){})vs Promise.try(function(){})的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该使用哪个?以下是相同的吗?

When should I use which? Are the following the same?

新的Promise()示例:

new Promise() example:

function multiRejectExample(){ 
  return new Promise(function (resolve, reject){
    if(statement){
      console.log('statement 1');
      reject(throw new Error('error'));
    }
    if(statement){
     console.log('statement 2');
     reject(throw new Error('error')); 
   }
  });
}

Promise.try()示例:

Promise.try() example:

function tryExample(){
  return Promise.try(function(){
    if(statement){
      console.log('statement 1');
      throw new Error('error');
    }
    if(statement){
     console.log('statement 2');
     throw new Error('error'); 
   }
  });
}


推荐答案

你可以在这种情况(有一个行为差异)。第一个是标准承诺功能,可以与任何promise库一起使用。

You can use mostly either in this case (with one behavior difference). The first is standard promise functionality and will work with any promise library.

Promise.try()是一个由Bluebird库专门实现的功能,不属于任何标准流程我知道。

Promise.try() is a feature specifically implemented by the Bluebird library and is not part of any standards process that I am aware of.

使用 Promise.try()的原因是你有一个函数返回一个promise,但生成该promise的代码也可能导致同步异常。由于该异常不在任何promise处理程序中,因此您可以混合使用错误处理。某些代码执行路径可能会导致返回将要解析或拒绝的promise,而其他代码执行路径可能会引发异常。要安全地编写代码,你必须同时响应promise并在代码周围放置一个try / catch块,这些代码变得笨拙。

The reason to use Promise.try() is if you have a function that returns a promise, but the code that generates that promise might also cause a synchronous exception. Since that exception is not inside of any promise handler, you'd have a mix of error handling. Some code execution paths might cause a promise to be returned that would resolve or reject and other code execution paths might throw an exception. To code this safely, you'd have to both respond to the promise and put a try/catch block around the code which gets unwieldy.

Promise.try()只是一种自动捕获任何异常并将其变为拒绝的方法(类似于 .then()中发生的情况处理程序)。

Promise.try() is simply a means of automatically catching any exceptions and turning them into a rejection (similar to what happens in .then() handlers).

在这两种情况下, Promise.try()不会以这种方式使您受益,因为 new Promise() callback已经捕获异常并将其变为拒绝,以便在那里为您完成功能。您可以在此处看到: http://jsfiddle.net/jfriend00/wLov9844/

In your two cases, Promise.try() does not benefit you in that way because the new Promise() callback already catches exceptions and turns them into rejections so that functionality is already being done for you there. You can see that demonstrated here: http://jsfiddle.net/jfriend00/wLov9844/

Bluebird doc提供了这个示例,它更清楚地显示了这个好处:

The Bluebird doc offers this example which shows the benefit more clearly:

function getUserById(id) {
    return Promise.try(function() {
        if (typeof id !== "number") {
            // Courtesy of Promise.try() this exception will be turned 
            // into a returned promise that is rejected with the 
            // exception as the reason
            throw new Error("id must be a number");
        }
        return db.getUserById(id);
    });
}

getUserById().then(successFn, errFn);

使用 Promise.try()这里确保 getUserById()将始终返回一个promise,即使该方法内部的代码同步抛出异常。这简化了 getUserById()的使用,因为您始终可以只响应承诺而不必使用自己的异常处理程序。

The use of Promise.try() here makes sure that getUserById() will always return a promise, even if the code inside of that method throws an exception synchronously. This simplifies use of getUserById() since you can always just respond to the promise and don't have to use your own exception handler around it.

如果没有 Promise.try(),你可以自己编写相同的代码(以捕获函数内所有可能的同步异常):

Without Promise.try(), you could code the same thing yourself like this (to catch all possible synchronous exceptions inside the function):

function getUserById(id) {
    try {
        if (typeof id !== "number") {
            throw new Error("id must be a number");
        }
        return db.getUserById(id);
    } catch(e) {
        return Promise.reject(e);
    }
}

getUserById().then(successFn, errFn);

或者,您可以这样编码:

Or, you could code it like this:

function getUserById(id) {
    if (typeof id !== "number") {
        throw new Error("id must be a number");
    }
    return db.getUserById(id);
}

try {
    getUserById().then(successFn, errFn);
} catch(e) {
    errFn(e);
}

据推测,你可以看到 Promise.try( )可以在某些情况下简化。

Presumably, you can see how Promise.try() can simplify things in some circumstances.

仅供参考,在你的第一个例子中,你是使用无效语法。你可以这样做:

FYI, in your first example, you are using invalid syntax. You can do this:

reject(throw new Error('error')); 

我假设你的意思是:

reject(new Error('error')); 






虽然我认为这不是真的你问的是, Promise.try()如果你自己没有回复承诺,也会自动返回已解决的承诺。由于您的第一个示例中的一条路径无法解决或拒绝,因此这会导致您的两个示例产生差异。


Though I don't think this is really what you were asking about, Promise.try() will also automatically return a resolved promise if you don't return a promise yourself. Since one path through your first example doesn't resolve or reject, this will cause a difference in your two examples.

这篇关于Bluebird.JS承诺:新Promise(函数(解析,拒绝){})vs Promise.try(function(){})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆