谈谈promise

金字塔类的嵌套

采用promise是为了解决层层嵌套式的地狱式回调,在这种回调里,return,throw都是不可用的而且堆栈还会被破坏。

正确的promise风格

new Promise(...).then(function () {
  return 
console.log(1);
}).then(function (resultOfPut) { return
console.log(2);
}).then(function (resultOfGet) {
console.log(3);
}).catch(function (err) { console.log(err);});

如何嵌套循环使用

new Promise()).then(function (result) {
return Promise.all(result.rows.map(function (row) { return row.remove(row.doc);
}));}).then(function () { //....});
对于promise。all()

Promise.all() 会将执行结果组成的数组返回到下一个函数,比如当你希望从 PouchDB 中获取多个对象时,会非常有用。此外一个更加有用的特效是,一旦数组中的 promise 任意一个返回错误,Promise.all() 也会返回错误。

catch

 很多Promise 库会在这种场景抛出 UnhandledRejectionError 警示有未处理的异常,这类情况一旦发现,就会造成脚本异常,所以要合适的写好catch();

Promise.resolve(),Promise.reject()


Promise.resolve(someSynchronousValue).then(/* ... */);
Promise.reject(new Error('some awful error'));

test1: promise穿透

Promise.resolve('foo').then(Promise.resolve('bar')).then(function (result) {
  console.log(result);
});
添加任意数量的  then(null) ,它依然会打印  foo

test2:抛出两个promise

getUserByName('nolan').then(function (user) {
  return getUserAccountById(user.id).then(function (userAccount) {
    // okay, I have both the "user" and the "userAccount"
  });
});
test3: catch()  与  then(null, ...)  并非完全等价

somePromise().then(function () {
  throw new Error('oh noes');
}).catch(function (err) {
  // I caught your error! 
});

somePromise().then(function () {
  throw new Error('oh noes');
}, function (err) {
  // I didn't catch your error!
});







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值