这两份承诺的着作是否相同吗?

时间:2017-09-10 10:26:31

标签: javascript promise

从教程书中我可以看到以下代码

  createShoppingList: (store, shoppinglist) => {
    return api.addNewShoppingList(shoppinglist).then(() => {
      store.dispatch('populateShoppingLists')
    }, () => {
      store.commit(types.ADD_SHOPPING_LIST, shoppinglist)
    })
  }

注意.then()块之后的逗号

它是否等同于链式.then()?

  createShoppingList: (store, shoppinglist) => {
    return api.addNewShoppingList(shoppinglist)
    .then(() => {
      store.dispatch('populateShoppingLists')
    })
    .then(() => {
      store.commit(types.ADD_SHOPPING_LIST, shoppinglist)
    })
  }

或者它只是.then()中的一个块? 喜欢:

return api.addNewShoppingList(shoppinglist)
.then(
() => { store.dispatch('populateShoppingLists')}, 
() => { store.commit(types.ADD_SHOPPING_LIST, shoppinglist) }
)

感谢您的反馈

2 个答案:

答案 0 :(得分:2)

没有

.then(resolved, rejected)

不等于

.then(resolve)
.then(rejected)// :/

它非常相似:

.then(resolved)    
.catch(rejected)

(Theres仍然不同于当时内部的拒绝将被捕获,而上层版本未被捕获)

答案 1 :(得分:0)

不,

.then(resolved, rejected)

更像是

.catch(rejected)
.then(resolved)

但不完全,与.then(resolved, rejected)一样,此函数的结果将转发给以下Promise,而不会相互转发。



var resolved = value => `resolve(${value})`;
var rejected = err => `catched(${err})`;
var throwing = () => { throw "thrown Error" };

Promise.resolve(42)
  .then(resolved, rejected)
  .then(v => console.log("then(a,b) => ", v));
  
Promise.reject(42)
  .catch(rejected)
  .then(resolved)
  .then(v => console.log("catch(b).then(a) => ", v));
  
//and that's why .then(a,b) ain't like .then(a).catch(b)
Promise.resolve(42)
  .then(throwing, rejected)  
  .then(v => console.log("then(throw,b) => ", v))
  .catch(err => console.log("then(throw,b) => ", err));


Promise.resolve(42)
  .then(throwing)
  .catch(rejected)  
  .then(v => console.log("then(throw).catch(b) => ", v))
  .catch(err => console.log("then(throw).catch(b) => ", err));

.as-console-wrapper{top:0;max-height:100%!important}