JavaScript Promise ve Promise Chaining

Bu eğitimde, örnekler yardımıyla JavaScript vaatleri ve zincirleme vaatleri hakkında bilgi edineceksiniz.

JavaScript'te söz, zaman uyumsuz işlemleri gerçekleştirmenin iyi bir yoludur . Eşzamansız işlemin başarıyla tamamlanıp tamamlanmadığını öğrenmek için kullanılır.

Bir söz, üç durumdan birine sahip olabilir.

  • Bekliyor
  • Yerine getirilmiştir
  • Reddedildi

Bir söz, bekleme durumunda başlar. Bu, işlemin tamamlanmadığı anlamına gelir. İşlem başarılı olursa, işlem tamamlanmış bir durumda sona erer. Ve bir hata oluşursa, süreç reddedilmiş bir durumda sona erer.

Örneğin, bir vaat kullanarak sunucudan veri talep ettiğinizde, bekleme durumunda olacaktır. Veriler başarıyla ulaştığında, yerine getirilmiş durumda olacaktır. Bir hata oluşursa, reddedilmiş durumda olacaktır.

Söz Oluşturun

Bir vaat nesnesi oluşturmak için yapıcıyı kullanırız Promise().

 let promise = new Promise(function(resolve, reject)( //do something ));

Promise()Yapıcı bir argüman olarak bir işlev alır. İşlev ayrıca iki işlevi kabul eder resolve()ve reject().

Söz başarıyla geri dönerse, resolve()işlev çağrılır. Ve bir hata meydana gelirse, reject()işlev çağrılır.

Aşağıdaki programın asenkron bir program olduğunu varsayalım. Daha sonra program bir söz kullanılarak ele alınabilir.

Örnek 1: Sözlü Program

 const count = true; let countValue = new Promise(function (resolve, reject) ( if (count) ( resolve("There is a count value."); ) else ( reject("There is no count value"); ) )); console.log(countValue);

Çıktı

 Söz (: "Bir sayım değeri vardır.")

Yukarıdaki programda, Promiseiki işlevi alan bir nesne oluşturulur: resolve()ve reject(). resolve()işlem başarılı olursa ve reject()sözde bir hata oluştuğunda kullanılır.

Count değeri doğruysa vaat çözülür.

JavaScript vaadiyle çalışmak

JavaScript Promise Chaining

Birden fazla eşzamansız görevi birbiri ardına halletmeniz gerektiğinde sözler yararlıdır. Bunun için söz zincirleme kullanıyoruz.

Sen bir söz yöntemleri kullanılarak çözüldükten sonra bir operasyon gerçekleştirebilir then(), catch()ve finally().

JavaScript sonra () yöntemi

then()Söz başarıyla yerine getirmiş veya çözüldüğünde yöntemi geri arama ile kullanılır.

then()Yöntemin sözdizimi şöyledir:

 promiseObject.then(onFulfilled, onRejected);

Örnek 2: Sözü Zincirleme ()

 // returns a promise let countValue = new Promise(function (resolve, reject) ( resolve('Promise resolved'); )); // executes when promise is resolved successfully countValue.then( function successValue(result) ( console.log(result); ), ) .then( function successValue1() ( console.log('You can call multiple functions this way.'); ), );

Çıktı

 Söz çözüldü Bu şekilde birden fazla işlevi çağırabilirsiniz.

Yukarıdaki programda, then()metot, fonksiyonları vaadi zincirlemek için kullanılır. then()Söz başarıyla çözüldüğünde yöntemi denir.

Sözle birden fazla then()yöntemi zincirleyebilirsiniz .

JavaScript catch () yöntemi

catch()Söz reddedildiğinde yöntemi geri arama ile kullanılır veya bir hata oluşursa. Örneğin,

 // returns a promise let countValue = new Promise(function (resolve, reject) ( reject('Promise rejected'); )); // executes when promise is resolved successfully countValue.then( function successValue(result) ( console.log(result); ), ) // executes if there is an error .catch( function errorValue(result) ( console.log(result); ) );

Çıktı

 Söz reddedildi

Yukarıdaki programda söz reddedilir. Ve catch()yöntem, hatayı halletme vaadi ile kullanılır.

JavaScript vaat zincirleme çalışması

JavaScript Promise Versus Callback

Sözler, her ikisinin de zaman uyumsuz görevleri yerine getirmek için kullanılabilmesi açısından geri arama işlevlerine benzer.

Eşzamanlı görevleri gerçekleştirmek için JavaScript geri çağırma işlevleri de kullanılabilir.

Farklılıkları şu noktalarda özetlenebilir:

JavaScript Sözü

  1. Sözdizimi kullanıcı dostudur ve okunması kolaydır.
  2. Hata işlemeyi yönetmek daha kolaydır.
  3. Misal:
     api (). sonra (işlev (sonuç) (dönüş api2 ();)). sonra (işlev (sonuç2) (dönüş api3 ();)). sonra (işlev (sonuç3) (// çalış)). catch ( function (hata) (// bu noktadan önce oluşabilecek herhangi bir hatayı ele alın));

JavaScript Geri Arama

  1. Sözdiziminin anlaşılması zor.
  2. Hata işlemeyi yönetmek zor olabilir.
  3. Misal:
     api (function (sonuç) (api2 (function (sonuç2) (api3 (function (sonuç3)) (// çalış if (hata) (// bir şeyler yap) else (// bir şeyler yap)));));)) ;

JavaScript nihayet () yöntemi

You can also use the finally() method with promises. The finally() method gets executed when the promise is either resolved successfully or rejected. For example,

 // returns a promise let countValue = new Promise(function (resolve, reject) ( // could be resolved or rejected resolve('Promise resolved'); )); // add other blocks of code countValue.finally( function greet() ( console.log('This code is executed.'); ) );

Output

 This code is executed.

JavaScript Promise Methods

There are various methods available to the Promise object.

Method Description
all(iterable) Waits for all promises to be resolved or any one to be rejected
allSettled(iterable) Waits until all promises are either resolved or rejected
any(iterable) Returns the promise value as soon as any one of the promises is fulfilled
race(iterable) Wait until any of the promises is resolved or rejected
reject(reason) Returns a new Promise object that is rejected for the given reason
resolve(value) Returns a new Promise object that is resolved with the given value
catch() Appends the rejection handler callback
then() Appends the resolved handler callback
finally() Appends a handler to the promise

To learn more about promises in detail, visit JavaScript Promises.

Ilginç makaleler...