Asynchronous Programming in JavaScript,
JSON and AJAX
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
April 3, 2025
Synchronous system
Asynchronous system
JavaScript offers three main asynchronous tools:
callbackFn
or the anonymous function right away.Name | Description |
---|---|
setTimeout(callBack, delayMS) |
Arranges to call given function after given delayMS, returns timer id |
setInterval(callBack, delayMS) |
Arranges to call function repeatedly every delayMS ms, returns timer id |
clearTimeout(timerID) |
Stop the given timer |
clearInterval(timerID) |
Stop the given interval |
setTimeout
and setInterval
.setTimeout
and setInterval
return an ID representing the timer.clearTimeout
/clearInterval
latersetTimeout
exampleHTML code
JS code
document.addEventListener('DOMContentLoaded', init);
function init() {
id("demo-btn").addEventListener("click", delayedMessage);
}
function delayedMessage() {
id("output-text").textContent = "It's gonna be legend...wait for it...";
setTimeout(sayHello, 3000);
}
function sayHello() { // called when the timer goes off
id("output-text").textContent = "dary... Legendary!";
}
setInterval
exampleHTML code
JS code
cb
receives two arguments, an error and a result.Promise
object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.then
method is employed, while the catch
method is used to address the rejection of the promise.fetch
to make a request to an external application programming interface (API).fetch('https://pokeapi.co/api/v2/pokemon/gengar')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
excutorFn
in the code example).excutorFN
eventually determines the state of the promisePromise
always initially has a state of pendingsetTimeoutPromise
that receives a time as an argument.function setTimeoutPromise(time) {
function executorFunction(resolve, reject) {
setTimeout(function () {
resolve();
}, time);
}
return new Promise(executorFunction);
}
console.log('Before setTimeoutPromise');
setTimeoutPromise(1000).then(function () {
console.log('one second later');
});
console.log('After setTimeoutPromise');
Promises are a great way to deal with the limitations that callbacks introduce when we need to perform multiple asynchronous operations that should be executed in a consecutive order.
Promises will handle errors more easily, so the readability of the code should be clearer and easier to maintain in long term.
readFile("docs.md") // returns a Promise
.then(convertMarkdownToHTML) // gets the content of docs.md
.then(addCssStyles) // gets the HTML from the previous step
.then(docs => saveFile(docs, "docs.html")) // saves the final version
.then(ftp.sync) // syncs to the server
.then(result => {
// do something with result
})
.catch(error => console.log(error));
then(...)
receives the resolved value from the previous Promise, and passes its own result to the next .then()
.
async
and await
keywords.async
wraps the return value in a Promise whose resolved value is the return valueawait
halts execution of the code within scope of the function it’s defined in until the Promise is resolved and then returns the resolved value of the promiseasync
keyword (trivial example)await
keyword (trivial example)function newPromise(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time, 'wow');
});
}
// Example 1: Using .then() to handle the resolved value
let example1 = newPromise(2000);
example1.then(result => {
console.log(result + ' that was simple (promise)');
});
// Example 2: Using await (inside an async function)
async function runExample2(time) {
let example2 = await newPromise(time);
console.log(example2 + ' that was simple (async/await');
}
runExample2(4000);
await
means that we are halting the execution of our code until the Promise has resolved (or rejected)await
keyword inside of a function, the functions needs to be labeled as async
async
functions need to be awaited when calledasync
/await
Backend development and Introduction to Node.js
Web Programming