Method catch() mengembalikan Promise dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method Promise.prototype.then(undefined, onRejected).

Sintaks

p.catch(onRejected);

p.catch(function(reason) {
   // rejection
});

Parameter

onRejected
 Function dipanggil ketika Promise ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.

Deskripsi

Method catch sangat berguna untuk menangani error di gabungan promis anda.

Contoh

Penggunaan method catch

var p1 = new Promise(function(resolve, reject) {
  resolve('Success');
});

p1.then(function(value) {
  console.log(value); // "Success!"
  throw 'oh, no!';
}).catch(function(e) {
  console.log(e); // "oh, no!"
}).then(function(){
  console.log('after a catch the chain is restored');
}, function () {
  console.log('Not fired due to the catch');
});

// The following behaves the same as above
p1.then(function(value) {
  console.log(value); // "Success!"
  return Promise.reject('oh, no!');
}).catch(function(e) {
  console.log(e); // "oh, no!"
}).then(function(){
  console.log('after a catch the chain is restored');
}, function () {
  console.log('Not fired due to the catch');
});

Promis tidak dapat mendeteksi error pada asynchronous callback

var p1 = new Promise(function(resolve, reject) {
  throw 'Uh-oh!';
});

p1.catch(function(e) {
  console.log(e); // "Uh-oh!"
});


var p2 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    throw 'Uncaught Exception!';
  }, 1000);
});

p2.catch(function(e) {
  console.log(e); // This is never called
});

Spesifikasi

Spesifikasi Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise.prototype.catch' in that specification.
Standard Initial definition in an ECMA standard.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Promise.prototype.catch' in that specification.
Draft  

Kompabilitas Browser

 

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 32Edge Full support YesFirefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Edge Mobile Full support YesFirefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support

 

Lihat Juga

Tag Dokumen dan Kontributor

Kontributor untuk laman ini: fscholz, bekti
Terakhir diperbarui oleh: fscholz,