金字塔类的嵌套
采用promise是为了解决层层嵌套式的地狱式回调,在这种回调里,return,throw都是不可用的而且堆栈还会被破坏。
正确的promise风格
new Promise(...).then(function () { return
}).then(function (resultOfPut) { returnconsole.log(1);
}).then(function (resultOfGet) {console.log(2);
}).catch(function (err) { console.log(err);});console.log(3);
如何嵌套循环使用
对于promise。all()return Promise.all(result.rows.map(function (row) { returnnew Promise()
).then(function (result) {row
.remove(row.doc);
}));}).then(function () { //....});
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!
});