您是否应该在承诺中解决或拒绝后返回某些内容?

时间:2016-10-20 07:02:39

标签: javascript promise ecmascript-6 es6-promise

假设我有以下的承诺:

new Promise((resolve, reject) => {

  // Some random conditional
  if (today === 'Friday') {
    console.log("I'm resolving this thing here");
    resolve('taco');
    // Should I have a return true or false here?
  }

  console.log("Code made it past the first resolve");

  // Do some other code here, like connect to a database or API or something.
  connectToDatabase(function(result){
    // result was 'hamburger'
    resolve(result);
  });

}).then((value) => {
  console.log(value);
});

在这个例子中,我得到以下输出:

I'm resolving this thing here
Code made it past the first resolve
taco

因此,在我执行resolve之后,Promise代码继续执行。在上面的示例中,我不必要地连接到某个数据库或端点或其他东西。显然,忽略了发送resolve,这很好。但从服务成本的角度来看,连接到数据库和API的成本很高,特别是如果每​​次发出类似AWS服务的请求时都会花费你的钱。

所以我的问题是,我应该在第一个return true;之后加入resolve或其他内容吗?

reject类似,我应该在return false之后加入reject或(true ??)吗?

new Promise((resolve, reject) => {
  someAsyncFunction((err, result) => {
    if (err) {
      reject(err);
      // Should I have a return true or false here or something?
    }

    // Do something here, like connect to a database or fetch a value from some API endpoint or something.

    resolve(result);
  });
});

如果我不希望代码在reject之后执行,我应该返回,是吗?

当我查看各种ES6文档时,我无法找到他们明确表达的任何地方......许多Promise示例通常都会非常简化。

如果我确实遗漏了这些东西,我该怎么回事? truefalse?还是return resolve('taco');

1 个答案:

答案 0 :(得分:-3)

基本层面理解承诺如何运作以及何时使用解决,拒绝

   function d() {
     console.log("D started");
     return Promise.reject(new Error("Aborted from D function"));

   //return Promise.resolve("Done with D");
 }

function c() {
console.log("C Started");
//return Promise.reject(new Error("Aborted from C function"));
//return Promise.resolve("Done with C");
return d().then(result => {
       return Promise.resolve(result);  
}).catch(err => {
       return Promise.reject(new Error(err));
});
}

function b() {
  console.log("B Started");
  //return Promise.reject(new Error("Aborted from B function"));
 return Promise.resolve("Done With B");
   }

    function a() {
    console.log("A started");
    return b().then(function(resultb){
        console.log("B result:"+resultb);
        return c();
 }).catch(function(err){
        console.log("Error:"+err)
}).then(function(resultc){
       console.log("C result:"+resultc)
}).catch(function(err){
    console.log("Error:"+err);  
  });
   }

  a();