--- title: Graceful asynchronous programming with Promises slug: Learn/JavaScript/Asynchronous/Promises translation_of: Learn/JavaScript/Asynchronous/Promises ---
Promises הן תכונה חדשה יחסית ב-JavaScript, אשר מאפשרת לנו לדחות פעולות מסוייומות עד אשר פעולותדמות להן יושלמו, או שיגיבו לכך שהן נכשלו. זוהי תכונה מאוד שימושית על מנת ליצור רצף של פעולות א-סינכרוניות שיעבדו בצור הטובה. מאמר זה נועד להסביר כיצד promises עובדות, כיצד אנו נראה אותם בשימוש ב-web APIs וכיצד נכתוב promises משלנו.
ידע מוקדם: | Basic computer literacy, a reasonable understanding of JavaScript fundamentals. |
---|---|
מטרה: | להבין מהן promises וכיצד להשתמש בהן. |
סקרנו קצת Promises במאמר הראשון במודול זה, אבל במאמר זה נסקור אותן יותר לעומק.?
בעיקרון promise הוא בעצם אובייקט שמייצג מצב ביניים של פעולה - בפועל, promise היא מעין הבטחה שתוצאה מסויימת תוחזר בנקודה מסויימת בעתיד. אין שום הבטחה מתי הפעולה תושלם ומתי התוצאה תוחזר, אבל יש הבטחה שכאשר התוצאה מוכנה, או שכאשר הפעוללה נכשלה, הקוד שסיפקנו ירוץ על מנת לעשות משהו עם תוצאה מוצלחת או להתמודד עם כשלון בפעולה.
באופן כללי, אנחנו פחות מתעניינים בזמן שייקח לפעולה א-סינכרונית להחזיר את התוצאה שלה (אלא אם כן מדובר בזמן יותר מדי ארוך), ואנחנו יותר מעוניינים בכך שתהיה לנו אפשרות להגיב לאותה תגובה כאשר היא תחזור, לא משנה מהי התגובה. וכמובן, זה נחמד שאותה פעולה לא חוסמת את הקוד מלרוץ.
אחד מהשימושים של promise שאנחנו נראה הוא ב-web APIs שמחזירים promise. נניח ויש לנו יישום וידאו צ׳אט. ליישום זה יש חלון עם רשימת החברים של המשתמש, ובלחיצה על כפתור ליד שם החבר, תחל שיחת וידאו עם אותו חבר.
מטפל האירוע של הכפתור הזה קורא ל- {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} על מנת לקבל גישה למיקרופון ולמצלמה של המשתמש. מאחר ו-()getUserMedia
חייב לוודא שלמשתמש יש אישור להשתמש באותם מכשירים ולבקש מהמשתמש לבחור איזה מיקרופון ואיזו מצלמה להשתמש בהם או בכל שילוב אחר. בזמן הבקשה הזו, פעולה זו יכולה לחסום את המשך התוכנית לא רק עד אשר כל האישורים האלו התקבלו, אלא גם עד אשר המצלמה והמיקרופון יתחברו. בנוסף, המשתמש אולי לא יגיב באופן מיידי לבקשות אלו. זה יכול לקחת הרבה זמן.
מאחר והקריאה ל- ()getUserMedia
נעשית מה- browser's main thread, הדפדפן חסום עד אשר ()getUserMedia
תסיים. ברור כמובן שזו לא אפשרות מקובלת בימים אלו. ללא promises, כל דבר בדפדפן היה נהפך ללא שימושי עד אשר המשתמש יחליט מה לעשות עם המצלמה והמיקרופון. אז במקום לחכות למשתמש, לקבל את המכשירים שנבחרו, ולהחזיר את ה-{{domxref("MediaStream")}} שנוצר למקורות אלו, ()getUserMedia
מחזיר {{jsxref("promise")}} אשר נפתר עם {{domxref("MediaStream")}} ברגע שהוא זמין.
הקוד של יישום הוידאו צאט שלנו, עשוי להיראות כך?:?
function handleCallButton(evt) { setStatusMessage("Calling..."); navigator.mediaDevices.getUserMedia({video: true, audio: true}) .then(chatStream => { selfViewElem.srcObject = chatStream; chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream)); setStatusMessage("Connected"); }).catch(err => { setStatusMessage("Failed to connect"); }); }
הפונקציה הזו מתחילה בכך שהיא משתמש בפונקציה שנקראת ()setStatusMessage
על מנת לעדכן שורת עדכון למשתמש עם הטקסט: "Calling...", שמעידה על כך שמבוצע ניסיול החל בשיחה. לאחר מכן היא קוראת לפונקציה ()getUserMedia
, ומבקשת שתחל בסטרים (stream) ?שיש לו גם וידאו וגם אודיו וברגע שהסטרים יהיה מוכן, היא ממשיכה בפעולות לשם הקמת הסטרים וחיבור המצלמה והאודיו. לאחר מכן היא מציגה למשתמש הודעה ״Connected״.
אם ()getUserMedia
תיכשל, בלוק הקוד של catch
ירוץ. הוא משתמש שוב ב- ()setStatusMessage
על מנת להציג למשתמש שהתרחשה שגיאה.
הדבר החשוב כן הוא שהקריאה של ()getUserMedia
מוחזרת כמעט באופן מיידי, גם אם הסטרים של המצלמה לא התקבל עדיין. אפילו אם הפונקציה של ()handleCallButton
סיימה להריץ את הקוד שבתוכה והחזירה את השליטה לקוד שקרא לה, כאשר ()getUserMedia
תסיים את הפעולה שלה, בין אם בהצלחה ובין אם תתרחש שגיאה, פונקציה זו תקרא שוב לאותו מטפל אירוע שסיפקנו לה. כלומר, היישום ימשיך לעבוד ולא יחכה לזרם הוידאו ולא ימנע מיתר הקוד להמשיך לרוץ.
לתשומת לב: לפרטים נוספים אודות נושא מורכב זה של וידאו ואודיו, ראו Signaling and video calling.
על מנת להבין לעומק מדוע promises הן דבר טוב, יעזור לנו לחשוב על ה-callbacks המיושנות ולהבין מדוע הן בעייתיות.
ננסה להמחיש זאת באמצעות דוגמא להזמנת פיצה כאנלוגיה. יש מספר שלבים שאנחנו צריכים לעשות ולהשלים בהצלחה, אשר לא ממש הגיוני לבצע אותם בסדר אחר או לבצע אותם בסדר הנכון, אבל בלי לחכות שהשלב הקודם הסתיים:
עם ה-callbacks הישנות, קוד מופשט שלנו ייראה בערך כך:
chooseToppings(function(toppings) { placeOrder(toppings, function(order) { collectOrder(order, function(pizza) { eatPizza(pizza); }, failureCallback); }, failureCallback); }, failureCallback);
קוד זה הוא מבולגן וקשה להבנה, ולפעמים גם נקרא כ-callback hell, הוא גם דורש שהפונקציה ()failureCallback
תיקרא כמה פעמים (בעבור כל פונקציה משורשרת) ויש לו גם חסרונות נוספים.
Promises הופכות את סיטואציות כמו למעלה להרבה יותר פשוטות לכתיבה, פירוש וריצה. אם נציג את הקוד המופשט שלנו שוב באמצעות promises א-סינכרוניות, הוא ייראה כך:
chooseToppings() .then(function(toppings) { return placeOrder(toppings); }) .then(function(order) { return collectOrder(order); }) .then(function(pizza) { eatPizza(pizza); }) .catch(failureCallback);
זה כבר הרבה יותר טוב- הרבה יותר קל להבין מה קורה כאן והיינו צריכים רק בלוק קוד אחד של ()
catch.
בעבור כל השגיאות שאולי יתרחשו. כל הקוד הזה אינו חוסם את ה-main thread (כך שאנחנו יכולים להמשיך לראות טלווזיה עד אשר הפיצה תהיה מוכנה), וכל פעולה תחכה בוודאות עד אשר הפעולה הקודמת תסיים לפני שהיא תרוץ. אנחנו יכולים לקשור מספר פעולות א-סינכרוניות כך שיתרחשו אחת אחרי השנייה מכיוון שכל בלוק קוד של (.....)then.
מחזיר promise חדשה, שנפתח כאשר הקוד שבתוך ה-(.....)then.
הרלוונטי מסיים לרוץ.
באמצעות שימוש בפונקציות חץ (arrow functions), אנחנו אפילו יכולים להפוך את הקוד לעוד יותר פשוט:
chooseToppings() .then(toppings => placeOrder(toppings) ) .then(order => collectOrder(order) ) .then(pizza => eatPizza(pizza) ) .catch(failureCallback);
או אפילו בצורה הזו:
chooseToppings() .then(toppings => placeOrder(toppings)) .then(order => collectOrder(order)) .then(pizza => eatPizza(pizza)) .catch(failureCallback);
זה עובד מכיוון שעם פונקציות חץ, x <= ()
הוא סינטקסס חוקי והוא קיצור של {return x} <= ()
.
אנחנו אפילו יכולים לרשום את הקוד שלנו בצורה כזו, מאחר שהפונקציות רק מעביר את הארגומנטים שלהם בצורה ישירה, אין צורך באמת לשכבה נוספת של פונקציה:
chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback);
יחד עם זאת, סינטקס זה לא ניתן לשימוש שוב, ולא ממש ברור לקריאה.
לתשומת לב: אנחנו אפילו יכולים לעשות שיפורים נוספים בסינטקס באמצעות הסינטקס של async
/await
, אשר נסקור אותו בהמשך המודול.
בבסיס שלהן, promises דומות למאזיני אירוע - event lisenters אך עם הבדלים ביניהם:
Promises חשובות מאוד להבנה מכיוון שמרבית ה-Web API המודרניים משתמשים בהן בעבור פונקציות שעלולות לבצע פעולות ארוכות.
בהמשך המאמר הזה אנחנו נראה כיצד לכתוב promises משלנו, אבל כאן אנחנו נסכתל על דוגמאות פשוטות שאנחנו ניתקל בהן ב-Web API שונים.
בדוגמא הראשונה שלנו, אנחנו נשתמש במתודת fetch()
, על מנת להביא תמונה מהאינטרנט, במתודת {{domxref("Body.blob", "blob()")}} על מנת להמיר את התוכן הגולמי של התגובה שקיבלנו לאובייקט {{domxref("Blob")}} , ולאחר מכן נציג את אותו blob בתוך אלמנט {{htmlelement("img")}}. זהו מאוד דומה לדוגמא שהסתכלנו עליה במאמר הראשון במודול, אבל אנחנו נעשה את זה מעט שונה כך שאתם תבנו את ה-promise.
ראשית, הורידו את ה-HTML template ואת ה-image file שאנחנו נייבא.
הוסיפו אלמנט {{htmlelement("script")}} בתחתית ה-{{htmlelement("body")}} בקובץ ה-HTML.
בתוך האלמנט {{HTMLElement("script")}} , הוסיפו את השורה הבאה:
let promise = fetch('coffee.jpg');
שורה זו קוראת למתודת ()fetch
ומעבירה אליה כפרמטר את ה-URL של התמונה שאנחנו רוצים לייבא מהרשת. אנחנו מאחסנים את אובייקט ה-promise שיוחזר אלינו מ-()fetch
בתוך משתנה שנקרא לו promise. כפי שאמרנו בעבר, האובייקט הזה מייצג מצב ביניים שבהתחלה הוא לא הצלחה ולא כישלון - מצב זה נקרא pending.
()
then.
של אובייקט ה-promise. ה-callback בתוך בלוק הקוד של ()
then.
(שנקרא גם executor), ירוץ רק כאשר פעולת ה-promise תושלם בהצלחה ותחזיר אובייקט {{domxref("Response")}} - במונחי promise, כאשר ה-promise תגיע למצב של הושלמה, fulfilled. היא תעביר את האובייקט {{domxref("Response")}} כפרמטר. לתשומת לב: הדרך שבה הבלוק ()
then.
עובד היא דומה לדרך שבה אנחנו מוסיפים מאזין אירוע - event listener - לאובייקט באמצעות המתודה ()AddEventListener
. מאזין האירוע לא ירוץ עד אשר האירוע יתרחש (ובאותה נשימה, כאשר ה-promise הושלמה בהצלחה). ההבדל העיקרי ביניהם הוא ש-()
then.
ירוץ רק פעם אחת בכל פעם שמשתמשים בו ואילו מאזין האירוע יכול להיות מופעל כמה פעמים.
אנחנו מייד נריץ את מתודת ()blob
על התגובה הזו, על מנת לוודא שגוף התגובה הורד בהצלחה, וכאשר הוא זמין נהפוך אותו לאובייקט Blob
שאנחנו יכולים לעשות איתו משהו. התוצאה של זה תוחזר לנו כך :
response => response.blob()
שזה קיצור של:
function(response) { return response.blob(); }
עד כאן עם ההסבר, אנא הוסיפו את הקוד הבא מתחת לשורה הראשונה של JavaScript:
let promise2 = promise.then(response => response.blob());
כל קריאה ל-()
then.
יוצרת promise חדשה. זהו מאוד שימושי - מכיוון שמתודת - ()blob
מחזירה גם היא promise, אנחנו יכולים לטפל באובייקט ה-Blob
שהיא מחזירה בעת ההשלמה שלו באמצעות הפעלה של מתודת ()
then.
על ה-promise השנייה. מכיוון שאנחנו רוצים לעשות משהו קצת יותר מורכב לאותו blob מאשר רק להריץ מתודה אחת עליו ולהחזיר את התוצאה, אנחנו צריכים לעטוף את גוף הפונקצייה בסוגריים מסולסלות - אחרת זה יגרום לשגיאה. הוסיפו את השורה הבאה מתחת לקוד הנוכחי שלכם:
let promise3 = promise2.then(myBlob => { })
כעת, נכניס את הקוד הבא שהוא הפונקציה שתופעל, לתוך הסוגריים המסולסלות:
let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image);
מה שעשינו כאן אנחנו מריצים בעצם מריצים מתודת {{domxref("URL.createObjectURL()")}} , מעבירים אליה כפרמרט את ה-Blob
שהוחזר אלינו כאשר ה-promise השנייה הושלמה. זה מחזיר לנו URL שמצביע על האובייקט. לאחר מכן יצרנו אלמנט {{htmlelement("img")}} , וקבענו את ה-src
שלו שיהיה שווה ל-URL של האובייקט ושייכנו אותו ל-DOM, כך שהתמונה תוצג על גבי הדף.
אם תשמרו ותרעננו את הדף, אתם תראו שהתמונה מוצגת על גבי הדף.
לתשומת לב: אתם בטח תשימו לב שדוגמאות אלו ארוכות מדי בשביל פעולה פשוטה שיכולנו לבצע באמצעות יצירת אלמנט <img>
וקביעת ה-src
שלו לאותו URL של התמונה במקום לעשות זאת באמצעות ()fetch
ובאמצעות ()blob
. יחד עם זאת, דוגמא זו נועדה על מנת להסביר בפשטות את תהליך ה-promises.
יש משהו חסר בדוגמא שלנו - כרגע, אין משהו שמגדיר כיצד להתמודד עם שגיאה כאשר ה-promise נכשלת, או rejects במונחים של promises. אנחנו יכולים להוסיף טיפול בשגיאה באמצעות הרצת מתודת ()catch.
של ה-promise הקודמת:
let errorCase = promise3.catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); });
To see this in action, try misspelling the URL to the image and reloading the page. The error will be reported in the console of your browser's developer tools.
This doesn't do much more than it would if you just didn't bother including the .catch()
block at all, but think about it — this allows us to control error handling exactly how we want. In a real app, your .catch()
block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever.
Note: You can see our version of the example live (see the source code also).
This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then()
blocks (and also .catch()
blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub):
fetch('coffee.jpg') .then(response => response.blob()) .then(myBlob => { let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); });
Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then()
block's executor function.
Note: .then()
/.catch()
blocks in promises are basically the async equivalent of a try...catch
block in sync code. Bear in mind that synchronous try...catch
won't work in async code.
There was a lot to cover in the above section, so let's go back over it quickly to give you a short guide that you can bookmark and use to refresh your memory in the future. You should also go over the above section again a few more time to make sure these concepts stick.
.then()
block onto the end of the promise chain. The executor function inside the .then()
block will contain the promise's return value..catch()
block onto the end of the promise chain.The above example showed us some of the real basics of using promises. Now let's look at some more advanced features. For a start, chaining processes to occur one after the other is all fine, but what if you want to run some code only after a whole bunch of promises have all fulfilled?
You can do this with the ingeniously named Promise.all()
static method. This takes an array of promises as an input parameter and returns a new Promise
object that will fulfill only if and when all promises in the array fulfill. It looks something like this:
Promise.all([a, b, c]).then(values => { ... });
If they all fulfill, then chained .then()
block's executor function will be passed an array containing all those results as a parameter. If any of the promises passed to Promise.all()
reject, the whole block will reject.
This can be very useful. Imagine that we’re fetching information to dynamically populate a UI feature on our page with content. In many cases, it makes sense to receive all the data and only then show the complete content, rather than displaying partial information.
Let's build another example to show this in action.
Download a fresh copy of our page template, and again put a <script>
element just before the closing </body>
tag.
Download our source files (coffee.jpg, tea.jpg, and description.txt), or feel free to substitute your own.
In our script we'll first define a function that returns the promises we want to send to Promise.all()
. This would be easy if we just wanted to run the Promise.all()
block in response to three fetch()
operations completing. We could just do something like:
let a = fetch(url1); let b = fetch(url2); let c = fetch(url3); Promise.all([a, b, c]).then(values => { ... });
When the promise is fulfilled, the values
passed into the fullfillment handler would contain three Response
objects, one for each of the fetch()
operations that have completed.
However, we don't want to do this. Our code doesn't care when the fetch()
operations are done. Instead, what we want is the loaded data. That means we want to run the Promise.all()
block when we get back usable blobs representing the images, and a usable text string. We can write a function that does this; add the following inside your <script>
element:
function fetchAndDecode(url, type) { return fetch(url).then(response => { if (type === 'blob') { return response.blob(); } else if (type === 'text') { return response.text(); } }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); }
This looks a bit complex, so let's run through it step by step:
fetch()
function to fetch the resource at the specified URL, then chain it onto another promise that returns the decoded (or "read") response body. This was always the blob()
method in the previous example.type
value is. Inside the executor function we include a simple if ... else if
statement to return a different promise depending on what type of file we need to decode (in this case we've got a choice of blob
or text
, but it would be easy to extend this to deal with other types as well).return
keyword before the fetch()
call. The effect this has is to run the entire chain and then run the final result (i.e. the promise returned by blob()
or text()
) as the return value of the function we've just defined. In effect, the return
statements pass the results back up the chain to the top.At the end of the block, we chain on a .catch()
call, to handle any error cases that may come up with any of the promises passed in the array to .all()
. If any of the promises reject, the catch block will let you know which one had a problem. The .all()
block (see below) will still fulfill, but just won't display the resources that had problems. If you wanted the .all
to reject, you'd have to chain the .catch()
block on to the end of there instead.
The code inside the function body is async and promise-based, therefore in effect the entire function acts like a promise — convenient.
Next, we call our function three times to begin the process of fetching and decoding the images and text, and store each of the returned promises in a variable. Add the following below your previous code:
let coffee = fetchAndDecode('coffee.jpg', 'blob'); let tea = fetchAndDecode('tea.jpg', 'blob'); let description = fetchAndDecode('description.txt', 'text');
Next, we will define a Promise.all()
block to run some code only when all three of the promises stored above have successfully fulfilled. To begin with, add a block with an empty executor inside the .then()
call, like so:
Promise.all([coffee, tea, description]).then(values => { });
You can see that it takes an array containing the promises as a parameter. The executor will only run when all three promises resolve; when that happens, it will be passed an array containing the results from the individual promises (i.e. the decoded response bodies), kind of like [coffee-results, tea-results, description-results].
Last of all, add the following inside the executor. Here we use some fairly simple sync code to store the results in separate variables (creating object URLs from the blobs), then display the images and text on the page.
console.log(values); // Store each value returned from the promises in separate variables; create object URLs from the blobs let objectURL1 = URL.createObjectURL(values[0]); let objectURL2 = URL.createObjectURL(values[1]); let descText = values[2]; // Display the images in <img> elements let image1 = document.createElement('img'); let image2 = document.createElement('img'); image1.src = objectURL1; image2.src = objectURL2; document.body.appendChild(image1); document.body.appendChild(image2); // Display the text in a paragraph let para = document.createElement('p'); para.textContent = descText; document.body.appendChild(para);
Save and refresh and you should see your UI components all loaded, albeit in a not particularly attractive way!
The code we provided here for displaying the items is fairly rudimentary, but works as an explainer for now.
Note: If you get stuck, you can compare your version of the code to ours, to see what it is meant to look like — see it live, and see the source code.
Note: If you were improving this code, you might want to loop through a list of items to display, fetching and decoding each one, and then loop through the results inside Promise.all()
, running a different function to display each one depending on what the type of code was. This would make it work for any number of items, not just three.
In addition, you could determine what the type of file is being fetched without needing an explicit type
property. You could for example check the {{HTTPHeader("Content-Type")}} HTTP header of the response in each case using response.headers.get("content-type")
, and then react accordingly.
There will be cases where you want to run a final block of code after a promise completes, regardless of whether it fulfilled or rejected. Previously you'd have to include the same code in both the .then()
and .catch()
callbacks, for example:
myPromise .then(response => { doSomething(response); runFinalCode(); }) .catch(e => { returnError(e); runFinalCode(); });
In more recent modern browsers, the .finally()
method is available, which can be chained onto the end of your regular promise chain allowing you to cut down on code repetition and do things more elegantly. The above code can now be written as follows:
myPromise .then(response => { doSomething(response); }) .catch(e => { returnError(e); }) .finally(() => { runFinalCode(); });
For a real example, take a look at our promise-finally.html demo (see the source code also). This works exactly the same as the Promise.all()
demo we looked at in the above section, except that in the fetchAndDecode()
function we chain a finally()
call on to the end of the chain:
function fetchAndDecode(url, type) { return fetch(url).then(response => { if(type === 'blob') { return response.blob(); } else if(type === 'text') { return response.text(); } }) .catch(e => { console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message); }) .finally(() => { console.log(`fetch attempt for "${url}" finished.`); }); }
This logs a simple message to the console to tell us when each fetch attempt has finished.
Note: finally()
allows you to write async equivalents to try/catch/finally in async code.
The good news is that, in a way, you've already built your own promises. When you've chained multiple promises together with .then()
blocks, or otherwise combined them to create custom functionality, you are already making your own custom async promise-based functions. Take our fetchAndDecode()
function from the previous examples, for example.
Combining different promise-based APIs together to create custom functionality is by far the most common way you'll do custom things with promises, and shows the flexibility and power of basing most modern APIs around the same principle. There is another way, however.
It is possible to build your own promises using the Promise()
constructor. The main situation in which you'll want to do this is when you've got code based on an an old-school asynchronous API that is not promise-based, which you want to promis-ify. This comes in handy when you need to use existing, older project code, libraries, or frameworks along with modern promise-based code.
Let's have a look at a simple example to get you started — here we wrap a setTimeout()
call with a promise — this runs a function after two seconds that resolves the promise (using the passed resolve()
call) with a string of "Success!".
let timeoutPromise = new Promise((resolve, reject) => { setTimeout(function(){ resolve('Success!'); }, 2000); });
resolve()
and reject()
are functions that you call to fulfill or reject the newly-created promise. In this case, the promise fulfills with a string of "Success!".
So when you call this promise, you can chain a .then()
block onto the end of it and it will be passed a string of "Success!". In the below code we simply alert that message:
timeoutPromise .then((message) => { alert(message); })
or even just
timeoutPromise.then(alert);
Try running this live to see the result (also see the source code).
The above example is not very flexible — the promise can only ever fulfill with a single string, and it doesn't have any kind of reject()
condition specified (admittedly, setTimeout()
doesn't really have a fail condition, so it doesn't matter for this simple example).
Note: Why resolve()
, and not fulfill()
? The answer we'll give you for now is it's complicated.
We can create a promise that rejects using the reject()
method — just like resolve()
, this takes a single value, but in this case it is the reason to reject with, i.e., the error that will be passed into the .catch()
block.
Let's extend the previous example to have some reject()
conditions as well as allowing different messages to be passed upon success.
Take a copy of the previous example, and replace the existing timeoutPromise()
definition with this:
function timeoutPromise(message, interval) { return new Promise((resolve, reject) => { if (message === '' || typeof message !== 'string') { reject('Message is empty or not a string'); } else if (interval < 0 || typeof interval !== 'number') { reject('Interval is negative or not a number'); } else { setTimeout(function(){ resolve(message); }, interval); } }); };
Here we are passing two arguments into a custom function — a message to do something with, and the time interval to pass before doing the thing. Inside the function we then return a new Promise
object — invoking the function will return the promise we want to use.
Inside the Promise constructor, we do a number of checks inside if ... else
structures:
setTimeout()
.Since the timeoutPromise()
function returns a Promise
, we can chain .then()
, .catch()
, etc. onto it to make use of its functionality. Let's use it now — replace the previous timeoutPromise
usage with this one:
timeoutPromise('Hello there!', 1000) .then(message => { alert(message); }) .catch(e => { console.log('Error: ' + e); });
When you save and run the code as is, after one second you'll get the message alerted. Now try setting the message to an empty string or the interval to a negative number, for example, and you'll be able to see the promise reject with the appropriate error messages! You could also try doing something else with the resolved message rather than just alerting it.
Note: You can find our version of this example on GitHub as custom-promise2.html (see also the source code).
The above example was kept deliberately simple to make the concepts easy to understand, but it is not really very async. The asynchronous nature is basically faked using setTimeout()
, although it does still show that promises are useful for creating a custom function with sensible flow of operations, good error handling, etc.
One example we'd like to invite you to study, which does show a useful async application of the Promise()
constructor, is Jake Archibald's idb library. This takes the IndexedDB API, which is an old-style callback-based API for storing and retrieving data on the client-side, and allows you to use it with promises. If you look at the main library file you'll see the same kind of techniques we discussed above being used there. The following block converts the basic request model used by many IndexedDB methods to use promises:
function promisifyRequest(request) { return new Promise(function(resolve, reject) { request.onsuccess = function() { resolve(request.result); }; request.onerror = function() { reject(request.error); }; }); }
This works by adding a couple of event handlers that fulfill and reject the promise at appropriate times:
request
's success
event fires, the onsuccess
handler fulfills the promise with the request result
.request
's error
event fires, the onerror
handler rejects the promise with the request error
.Promises are a good way to build asynchronous applications when we don’t know the return value of a function or how long it will take to return. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous try...catch
statement.
Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.
We didn't touch on all promise features in this article, just the most interesting and useful ones. As you start to learn more about promises, you'll come across further features and techniques.
Most modern Web APIs are promise-based, so you'll need to understand promises to get the most out of them. Among those APIs are WebRTC, Web Audio API, Media Capture and Streams, and many more. Promises will be more and more important as time goes on, so learning to use and understand them is an important step in learning modern JavaScript.
Promise()
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}