From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../global_objects/promise/all/index.html | 234 +++++++++++++++ .../global_objects/promise/catch/index.html | 201 +++++++++++++ .../reference/global_objects/promise/index.html | 317 +++++++++++++++++++++ 3 files changed, 752 insertions(+) create mode 100644 files/tr/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/promise/index.html (limited to 'files/tr/web/javascript/reference/global_objects/promise') diff --git a/files/tr/web/javascript/reference/global_objects/promise/all/index.html b/files/tr/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..cc57749d77 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,234 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +
{{JSRef}}
+ +

The Promise.all() method returns a single {{jsxref("Promise")}} that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

+ +
{{EmbedInteractiveExample("pages/js/promise-all.html")}}
+ + + +

Söz dizimi

+ +
Promise.all(iterable);
+ +

Parametreler

+ +
+
iterable
+
{{jsxref("Array")}} yada {{jsxref("String")}} gibi iterable nesnesi.
+
+ +

Dönen değer

+ + + +

Açıklama

+ +

This method can be useful for aggregating the results of multiple promises.

+ +

Fulfillment

+ +

The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

+ + + +

Rejection

+ +

If any of the passed-in promises reject, Promise.all asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved.

+ +

Örnekler

+ +

Promise.all Kullanımı

+ +

Promise.all tüm işlemler yerine getirilene kadar bekler (yada ilk reddedilmeye kadar).

+ +
var p1 = Promise.resolve(3);
+var p2 = 1337;
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(() => {
+    resolve("foo");
+  }, 100);
+});
+
+Promise.all([p1, p2, p3]).then(values => {
+  console.log(values); // [3, 1337, "foo"]
+});
+ +

If the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):

+ +
// this will be counted as if the iterable passed is empty, so it gets fulfilled
+var p = Promise.all([1,2,3]);
+// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled
+var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
+// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected
+var p3 = Promise.all([1,2,3, Promise.reject(555)]);
+
+// using setTimeout we can execute code after the stack is empty
+setTimeout(function() {
+    console.log(p);
+    console.log(p2);
+    console.log(p3);
+});
+
+// logs
+// Promise { <state>: "fulfilled", <value>: Array[3] }
+// Promise { <state>: "fulfilled", <value>: Array[4] }
+// Promise { <state>: "rejected", <reason>: 555 }
+ +

Asynchronicity or synchronicity of Promise.all

+ +

This following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of Promise.all:

+ +
// we are passing as argument an array of promises that are already resolved,
+// to trigger Promise.all as soon as possible
+var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
+
+var p = Promise.all(resolvedPromisesArray);
+// immediately logging the value of p
+console.log(p);
+
+// using setTimeout we can execute code after the stack is empty
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p);
+});
+
+// logs, in order:
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: Array[2] }
+
+ +

The same thing happens if Promise.all rejects:

+ +
var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
+var p = Promise.all(mixedPromisesArray);
+console.log(p);
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p);
+});
+
+// logs
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "rejected", <reason>: 44 }
+
+ +

But, Promise.all resolves synchronously if and only if the iterable passed is empty:

+ +
var p = Promise.all([]); // will be immediately resolved
+var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously
+console.log(p);
+console.log(p2)
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p2);
+});
+
+// logs
+// Promise { <state>: "fulfilled", <value>: Array[0] }
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: Array[2] }
+
+ +

Promise.all fail-fast behaviour

+ +

Promise.all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

+ +
var p1 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('one'), 1000);
+});
+var p2 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('two'), 2000);
+});
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('three'), 3000);
+});
+var p4 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('four'), 4000);
+});
+var p5 = new Promise((resolve, reject) => {
+  reject(new Error('reject'));
+});
+
+
+// Using .catch:
+Promise.all([p1, p2, p3, p4, p5])
+.then(values => {
+  console.log(values);
+})
+.catch(error => {
+  console.log(error.message)
+});
+
+//From console:
+//"reject"
+
+
+ +

It is possible to change this behaviour by handling possible rejections:

+ +
var p1 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('p1_delayed_resolvement'), 1000);
+});
+
+var p2 = new Promise((resolve, reject) => {
+  reject(new Error('p2_immediate_rejection'));
+});
+
+Promise.all([
+  p1.catch(error => { return error }),
+  p2.catch(error => { return error }),
+]).then(values => {
+  console.log(values[0]) // "p1_delayed_resolvement"
+  console.log(values[1]) // "Error: p2_immediate_rejection"
+})
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Promise.all")}}

+ +

See also

+ + diff --git a/files/tr/web/javascript/reference/global_objects/promise/catch/index.html b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..3360f87fbb --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,201 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - JavaScript + - Promise + - Prototype + - fonksiyon + - metod +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +
{{JSRef}}
+ +

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)). This means, that you have to provide onRejected function even if you want to fallback to undefined result value - for example obj.catch(() => {}).

+ +
{{EmbedInteractiveExample("pages/js/promise-catch.html")}}
+ + + + + + + +

Sözdizimi

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

Parametreler

+ +
+
onRejected
+
A {{jsxref("Function")}} called when the Promise is rejected. This function has one argument: +
+
reason
+
The rejection reason.
+
+ The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
+
+ +

Dönen değer

+ +

Internally calls Promise.prototype.then on the object upon which is called, passing the parameters undefined and the onRejected handler received; then returns the value of that call (which is a {{jsxref("Promise")}}).

+ +
+

Note the examples below are throwing instances of Error. This is considered good practice in contrast to throwing Strings: Otherwise the part doing the catching would have to make checks to see if the argument was a string or an error, and you might lose valuable information like stack traces.

+
+ +

Demonstration of the internal call:

+ +
// overriding original Promise.prototype.then/catch just to add some logs
+(function(Promise){
+    var originalThen = Promise.prototype.then;
+    var originalCatch = Promise.prototype.catch;
+
+    Promise.prototype.then = function(){
+        console.log('> > > > > > called .then on %o with arguments: %o', this, arguments);
+        return originalThen.apply(this, arguments);
+    };
+    Promise.prototype.catch = function(){
+        console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments);
+        return originalCatch.apply(this, arguments);
+    };
+
+})(this.Promise);
+
+
+
+// calling catch on an already resolved promise
+Promise.resolve().catch(function XXX(){});
+
+// logs:
+// > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()]
+// > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()]
+
+ +

Açıklama

+ +

The catch method can be useful for error handling in your promise composition.

+ +

Örnekler

+ +

Using and chaining the catch method

+ +
var p1 = new Promise(function(resolve, reject) {
+  resolve('Success');
+});
+
+p1.then(function(value) {
+  console.log(value); // "Success!"
+  throw new Error('oh, no!');
+}).catch(function(e) {
+  console.log(e.message); // "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');
+});
+
+ +

Gotchas when throwing errors

+ +
// Throwing an error will call the catch method most of the time
+var p1 = new Promise(function(resolve, reject) {
+  throw new Error('Uh-oh!');
+});
+
+p1.catch(function(e) {
+  console.log(e); // "Uh-oh!"
+});
+
+// Errors thrown inside asynchronous functions will act like uncaught errors
+var p2 = new Promise(function(resolve, reject) {
+  setTimeout(function() {
+    throw new Error('Uncaught Exception!');
+  }, 1000);
+});
+
+p2.catch(function(e) {
+  console.log(e); // This is never called
+});
+
+// Errors thrown after resolve is called will be silenced
+var p3 = new Promise(function(resolve, reject) {
+  resolve();
+  throw new Error('Silenced Exception!');
+});
+
+p3.catch(function(e) {
+   console.log(e); // This is never called
+});
+ +

If it is resolved

+ +
//Create a promise which would not call onReject
+var p1 = Promise.resolve("calling next");
+
+var p2 = p1.catch(function (reason) {
+    //This is never called
+    console.log("catch p1!");
+    console.log(reason);
+});
+
+p2.then(function (value) {
+    console.log("next promise's onFulfilled"); /* next promise's onFulfilled */
+    console.log(value); /* calling next */
+}, function (reason) {
+    console.log("next promise's onRejected");
+    console.log(reason);
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.builtins.Promise.catch")}}

+ +

Ayrıca bakınız

+ + diff --git a/files/tr/web/javascript/reference/global_objects/promise/index.html b/files/tr/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..90f9dcabc0 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - JavaScript + - Promise + - Referans +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +
Promise nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir Promise nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.
+ +
+ +

Sözdizimi

+ +
new Promise(function(resolve, reject) { ... });
+ +

Parametreler

+ +
+
executor
+
resolve ve reject içeren iki parametreli bir fonksiyon nesnesidir. İlk parametre promise nesnesi tamamlandığında, ikinci parametre ise reddettiğinde çağrılır. Bu fonksiyonları işlemimiz bittiğinde (başarılı yada başarısız) çağırırız.
+
+ +

Açıklama

+ +

Oluşturulan bir promise başka bir promise için proxy görevi görür.
+ Başarılı yada başarısız bir şekilde sonuç üreten asenkron işlemlerin ilişkilendirilmesine olanak tanır.Bu asenkron methodların senkron methodlar gibi sonuç döndürmesi'ni sağlar.Asenkron method hemen sonuçlanmaz.Bunun yerine işlemin tamamlandığı noktayı temsil eden bir promise döndürür.

+ +

Bir Promise şu durumları içerir:

+ + + +

Bekleyen bir Promise, bir sonuç döndürerek tamamlanabilir veya bir nedenle reddedilebilir(hata).Bunlardan herhanbiri gerçekleştiğinde (resolve/reject) sıraya konulmuş ilişkili methodlar sıra ile çağrılır.(Promise tamamlandığında yada red edildiğinde sırada bağlanmış bir method var ise o method çalıştırılır.Böylece asenkron işlemler arasında bir rekabet/mücadele olmaz.Sırası gelen çalışır.)

+ +

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, bunlar zincirlenebilirler—an operation called composition.

+ +

+ +
+

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.

+
+ +

Özellikler

+ +
+
Promise.length
+
Değeri 1 olan Length özelliği (constructor argümanları sayısı).
+
{{jsxref("Promise.prototype")}}
+
Represents the prototype for the Promise constructor.
+
+ +

Metodlar

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Belirtilen bir nedenden dolayı reddedilen Promise nesnesini döndürür.
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.
+
+ +

Promise prototype

+ +

Özellikler

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

+ +

Metodlar

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Örnekler

+ +

Promise Oluşturma

+ + + +

Bu küçük örnek Promise mekanizmasını gösterir. {{HTMLElement("button")}} her tıklandığında testPromise() metodu çağrılır . It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the string "result" every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

+ +

The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    var thisPromiseCount = ++promiseCount;
+
+    var log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise the string 'result' (after waiting 3s)
+    var p1 = new Promise(
+        // The resolver function is called with the ability to resolve or
+        // reject the promise
+        function(resolve, reject) {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // This is only an example to create asynchronism
+            window.setTimeout(
+                function() {
+                    // We fulfill the promise !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        });
+
+    // 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.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+ + + +

Bu örnek buton'a tıkladığınızda çalışır. Promise destekleyen bir tarayıcıya ihtiyacınız var. Buton'a birden fazla tıklamanız durumunda farklı promise nesnelerinin kısa sürede tamamlandığını göreceksiniz.

+ +

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

+ +

new XMLHttpRequest() Kullanım Örneği

+ +

Promise Oluşturma

+ +

Bu örnekte {{domxref("XMLHttpRequest")}} nesnesinin başarılı yada başarısız durumunu Promise kullanarak nasıl raporlanabildiğini göstermektedir.

+ +
'use strict';
+
+// A-> $http function is implemented in order to follow the standard Adapter pattern
+function $http(url){
+
+  // A small example of object
+  var core = {
+
+    // Method that performs the ajax request
+    ajax : function (method, url, args) {
+
+      // Creating a promise
+      var promise = new Promise( function (resolve, reject) {
+
+        // Instantiates the XMLHttpRequest
+        var client = new XMLHttpRequest();
+        var uri = url;
+
+        if (args && (method === 'POST' || method === 'PUT')) {
+          uri += '?';
+          var argcount = 0;
+          for (var key in args) {
+            if (args.hasOwnProperty(key)) {
+              if (argcount++) {
+                uri += '&';
+              }
+              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
+            }
+          }
+        }
+
+        client.open(method, uri);
+        client.send();
+
+        client.onload = function () {
+          if (this.status >= 200 && this.status < 300) {
+            // Performs the function "resolve" when this.status is equal to 2xx
+            resolve(this.response);
+          } else {
+            // Performs the function "reject" when this.status is different than 2xx
+            reject(this.statusText);
+          }
+        };
+        client.onerror = function () {
+          reject(this.statusText);
+        };
+      });
+
+      // Return the promise
+      return promise;
+    }
+  };
+
+  // Adapter pattern
+  return {
+    'get' : function(args) {
+      return core.ajax('GET', url, args);
+    },
+    'post' : function(args) {
+      return core.ajax('POST', url, args);
+    },
+    'put' : function(args) {
+      return core.ajax('PUT', url, args);
+    },
+    'delete' : function(args) {
+      return core.ajax('DELETE', url, args);
+    }
+  };
+};
+// End A
+
+// B-> Here you define its functions and its payload
+var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
+var payload = {
+  'topic' : 'js',
+  'q'     : 'Promise'
+};
+
+var callback = {
+  success : function(data){
+     console.log(1, 'success', JSON.parse(data));
+  },
+  error : function(data){
+     console.log(2, 'error', JSON.parse(data));
+  }
+};
+// End B
+
+// Executes the method call
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success)
+  .catch(callback.error);
+
+// Executes the method call but an alternative way (1) to handle Promise Reject case
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success, callback.error);
+
+// Executes the method call but an alternative way (2) to handle Promise Reject case
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success)
+  .then(undefined, callback.error);
+
+ +

XHR ile görsel yükleme

+ +

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationDurumYorum
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı uyumluluğu

+ + + +
+ + +

{{Compat("javascript.builtins.Promise")}}

+
+ + + +

Ayrıca bakınız

+ + -- cgit v1.2.3-54-g00ecf