Encadeando promessas Javascript
Estou tentando entender as promessas doDocumentação MDN. O primeiro exemplo demonstra athen
ecatch
métodos:
// We define what to do when the promise is resolved/fulfilled with the then() call,
// and the catch() method defines what to do if the promise is rejected.
p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
})
.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
A documentação afirma que othen
O método retorna uma nova promessa; portanto, o código acima não deve ser equivalente a
var p2 = p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
});
p2.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
?
Nesse caso, isso não significaria que ocatch
o retorno de chamada seria chamado apenas se a promessa retornada dep1.then
, não a promessap1
, resolvido para rejeitado? E eu não teria que fazer isso:
p1.then( /* etc. */ );
// and for rejected resolutions
p1.catch( /* etc. */ );
para pegar a rejeição da promessap1
em vez de encadear ocatch
aothen
?
No começo, pensei que a promessa retornasse dep1.then
era o mesmo quep1
, como o jQuery faz com muitas de suas APIs. Mas o seguinte mostra claramente que as duas promessas são diferentes.
var p1 = new Promise(function(resolve, reject) {
resolve("Success!");
});
console.log(p1);
// Promise { <state>: "fulfilled", <value>: "Success!" }
var p2 = p1.then(function(value) {
console.log(value);
});
// Success!
console.log(p2);
// Promise { <state>: "fulfilled", <value>: undefined }
Além disso, eu brinquei no JSFiddle com as três abordagens:
p1.then(onFulfilled).catch(onRejected);
p1.then(onFulfilled); p1.catch(onRejected);
p1.then(onFulfilled, onRejected);
Todos os três trabalham. Eu posso entender os dois últimos. A essência da minha pergunta é: por que a primeira abordagem também funciona?