CH13 Promise
CH13 Promise
Spring 2025
Promise
Yonsei University
• Synchronous
• Only one operation can be in progress at a time
• Asynchronous
• Allow a program to do more than one thing at a time
• Effectively handle potential blocking operations such as fetching a
resource from a server (TaskA) and applying a filter to it (TaskB)
can potentially
take a long time
TaskB
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous
2
Promise CAS2109-01
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing
3
Promise CAS2109-01
• If we add a text box for you to type in. This time, click "Generate
primes", and try typing in the text box immediately after
• The program is completely unresponsive: can't type anything
5
Promise CAS2109-01
1 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
6
Promise CAS2109-01
setTimeout(callback, 2000);
https://www.w3schools.com/jsref/met_win_settimeout.asp
7
Promise CAS2109-01
8
Promise CAS2109-01
10
Promise CAS2109-01
[ {
{ "name" : "mushy peas",
"name" : "baked beans", "price" : 0.58,
"price" : 0.40, "image" : "mushypeas.jpg",
"image" : "beans.jpg", "type" : "vegetables"
"type" : "vegetables" },
}, {
{ "name" : "corned beef",
"name" : "hot dogs", "price" : 2.39,
"price" : 1.99, "image" : "cornedbeef.jpg",
"image" : "hotdogs.jpg", "type" : "meat"
"type" : "meat" },
}, {
{ "name" : "tomato soup",
"name" : "spam", "price" : 1.40,
"price" : 2.85, "image" : "tomatosoup.jpg",
"image" : "spam.jpg", "type" : "soup"
"type" : "meat" },
}, products.json {
{ "name" : "chopped tomatoes",
"name" : "refried beans", "price" : 0.45,
"price" : 0.99, "image" : "tomato.jpg",
"image" : "refried.jpg", "type" : "vegetables"
"type" : "vegetables" },
}, {
{ "name" : "chicken noodle soup",
"name" : "kidney beans", "price" : 1.89,
"price" : 0.58, "image" : "chickennoodle.jpg",
"image" : "kidney.jpg", "type" : "soup"
"type" : "vegetables" },
}, {
{ "name" : "carrot and coriander soup",
"name" : "garden peas", "price" : 1.49,
"price" : 0.52, "image" : "carrotcoriander.jpg",
"image" : "gardenpeas.jpg", "type" : "soup"
"type" : "vegetables" }
}, ]
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json 12
Promise CAS2109-01
동영상
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/ 13
Promise CAS2109-01
console.log ('Starting');
let image;
fetch('coffee.jpg').then((response) => {
console.log('It worked :)')
return response.blob(); // Binary Large Object (이미지, 사운드, 비디오)
}).then((myBlob) => {
let objectURL = URL.createObjectURL(myBlob); // URL 생성
image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}).catch((error) => {
console.log('There has been a problem with your fetch operation: ' +
error.message);
});
console.log ('All done!');
14
Promise CAS2109-01
console.log ('Starting');
let image;
fetch('coffee.jpg').then((response) => {
console.log('It worked :)')
return response.blob(); //returns a Promise object1
}).then((myBlob) => {
let objectURL = URL.createObjectURL(myBlob);
image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}).catch((error) => {
console.log('There has been a problem with your fetch operation: ' +
error.message);
});
console.log ('All done! ' + image.src + ' displayed.');
TypeError: image is undefined; can't access its "src" property
1 https://developer.mozilla.org/en-US/docs/Web/API/Response/blob 15
Promise CAS2109-01
• Let’s make the three console.log() statements appear in the desired order
console.log ('Starting');
let image;
fetch('coffee.jpg').then((response) => {
console.log('It worked :)')
return response.blob();
}).then((myBlob) => {
let objectURL = URL.createObjectURL(myBlob);
image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}).then(() => {
console.log ('All done! ' + image.src + ' displayed.');
}).catch((err) => {
console.log('There has been a problem with your fetch operation: ' + err.message);
});
16
JavaScript CSI-2109-01
1 https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises
2 “coming or happening at a later time” 17
Promise CAS2109-01
18
Promise CAS2109-01
• Contains a handler that will run when the fetch operation succeeds
• The promise will call the handler, passing in a Response object2, which
contains the server's response
1 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
2 https://developer.mozilla.org/en-US/docs/Web/API/Response
19
Promise CAS2109-01
https://www.w3schools.com/js/js_promise.asp
20
Promise CAS2109-01
동영상1
22
Promise CAS2109-01
http://api.exchangeratesapi.io/
23
Promise CAS2109-01
24
Promise CAS2109-01
25
Promise CAS2109-01
26
Promise CAS2109-01
27
Promise 동영상 CAS2109-01
28
Promise CAS2109-01
29
Promise CAS2109-01
chooseToppings() chooseToppings()
.then(function(toppings) { .then(toppings =>
return placeOrder(toppings); placeOrder(toppings)
}) )
.then(function(order) { .then(order =>
return collectOrder(order); collectOrder(order)
}) )
.then(function(pizza) { .then(pizza =>
eatPizza(pizza); eatPizza(pizza)
}) )
.catch(failureCallback); .catch(failureCallback);
30
Promise CAS2109-01
• finally() method
• Run a final block of code after a promise completes
• Regardless of whether it fulfilled or rejected
myPromise myPromise
.then(response => {
.then(response => {
doSomething(response);
doSomething(response); })
runFinalCode(); .catch(e => {
}) returnError(e);
})
.catch(e => {
.finally(() => {
returnError(e);
runFinalCode();
runFinalCode(); });
});
31
Promise CAS2109-01
32
Promise CAS2109-01
• What if you want to run some code only after a whole bunch of
promises have all fulfilled?
33
Promise CAS2109-01
https://developers.google.com/web/fundamentals/primers/async-functions
34
Promise CAS2109-01
• To actually consume the value returned when the promise fulfills, use then()
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await
35
Promise CAS2109-01
36
Promise CAS2109-01
fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return 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:' + e.message);
});
37
Promise CAS2109-01
39