Async
1. Synchronous and Asynchronous
Synchronous
Waiting for specific code execution to complete before performing the next code
Asynchronous
Not waiting for specific code execution to complete, but performing the next code
2. Asynchronous JavaScript (Timer API)
setTimeout(callback, millisecond)
setTimeout(function () {
console.log('Execute after 1 second');
}, 1000);
/// 123
Execute a function after a certain time
parameter: callback function to execute, time to wait before executing the callback function (milliseconds)
return value: arbitrary timer ID
clearTimeout(timerId)
const timer = setTimeout(function () {
console.log('Execute after 10 seconds');
}, 10000);
clearTimeout(timer);
// setTimeout terminated
Terminate
setTimeout
timerparameter: timer ID
return value: none
setInterval(callback, millisecond)
setInterval(function () {
console.log('Execute every 1 second');
}, 1000);
/// 345
Execute a function repeatedly at regular time intervals
parameter: callback function to execute, time interval for repeatedly executing the function (milliseconds)
return value: arbitrary timer ID
clearInterval(timerId)
const timer = setInterval(function () {
console.log('Execute every 1 second');
}, 1000);
clearInterval(timer);
// setInterval terminated
Terminate
setInterval
timerparameter: timer ID
return value: none
3. Callback
One way to control code asynchronously is to utilize
callback
functionsHowever, as code gets longer, callback Hell occurs, making it complex and reducing readability
4. Promise
new Promise
Promise
is a class, so create aPromise
object using thenew
keywordPromise
takes a callback function that performs asynchronous processing as an argument, and this callback function receivesresolve
andreject
functions as argumentsWhen a
Promise
object is created, the callback function is automatically executedIf the code is processed well, call the
resolve
function, and if an error occurs, call thereject
functionlet promise = new Promise((resove, reject) => { // 1. When processed normally, pass value to resolve's argument resolve(value); // 2. When error occurs, pass error message to reject's argument reject(value); });
Promise Object's Internal Properties
The Promise object returned by
new Promise
hasstate
andresult
internal propertiesHowever, cannot access directly and must use
.then
,.catch
,.finally
methods to access
State
Default state is
pending
. If the callback function performing asynchronous processing works well → changes tofulfilled
, if error occurs →rejected
Result
Default state is
undefined
. If the callback function performing asynchronous processing works well andresolve(value)
is called → changes to value, if error occurs andreject(error)
is called → changes toerror
Then
If the code written in the callback function is processed well, call the
resolve
function → can access through.then
methodIf the value returned in
.then
is aPromise
, receive thePromise
's internal propertyresult
as the argument of the next.then
's callback functionIf it's not a
Promise
, can receive the returned value as the argument of.then
's callback functionlet promise = new Promise((resolve, reject) => { resolve('Success'); }); promise.then((value) => { console.log(value); // "Success" });
Catch
When an error occurs in the code written in the callback function, call the
reject
function and can access through.catch
methodlet promise = new Promise(function (resolve, reject) { reject(new Error('Error')); }); promise.catch((error) => { console.log(error); // Error: Error });
Finally
Can access through
.finally
method regardless of whether the code written in the callback function is processed normallylet promise = new Promise(function (resolve, reject) { resolve('Success'); }); promise .then((value) => { console.log(value); // "Success" }) .catch((error) => { console.log(error); }) .finally(() => { console.log('Works whether success or failure'); // "Works whether success or failure" });
Promise Chaining
When asynchronous tasks need to be performed sequentially
Promise all()
Used when you want to process multiple asynchronous tasks simultaneously
Takes an array as an argument, and if all the code written in the callback functions of all
Promise
in that array is processed normally, stores the results in an array and returns a newPromise
Additionally, if any of the
Promise
in the argument array encounters an error, immediately terminates regardless of the state of the remainingPromise
Promise.all([promiseOne(), promiseTwo(), promiseThree()]) .then((value) => console.log(value)) // ['1초', '2초', '3초'] .catch((err) => console.log(err));
5. Async, Await
Can write complex
Promise
code concisely usingasync
andawait
Use
async
before a function and use theawait
keyword only insideasync
functions: code written this way runs the next code after the code with theawait
keyword runs// Function declaration async function funcDeclarations() { await code you want to write ... } // Function expression const funcExpression = async function () { await code you want to write ... } // Arrow function const ArrowFunc = async() => { await code you want to write ... }
6. fetch API
fetch API
Role of receiving information from a specific URL
This process is asynchronous, so it may take some time depending on the situation
let url = 'https://koreanjson.com/posts/1'; fetch(url) .then((response) => response.json()) .then((json) => console.log(json)) .catch((error) => console.log(error));
7. Axios
A library that performs a similar role to fetch API
An HTTP asynchronous communication library that utilizes Promise API for browsers and Node.js
Easier to use than Fetch API with additional features included
A third-party library that requires installation
Automatically converts to JSON data format
GET Request
axios.get("url"[,config])
POST Request
axios.post("url"[, data[, config]])
Last updated