Coding Languages/JavaScript
[JavaScript] Async and Promise
brightlightkim
2022. 3. 25. 09:05
Async and Promises
- Async
- Do others while it’s working
- Do things that take long time (json from web service)
- Synchronous
- Block execution of work
- MIxing Synchronous and Asynchronous
- Possible Problems
- Know when synchronous and how to handle it (callbacks)
- callBack function (one problem)
- Another callback. (old ways)
- Possible Solutions
- callBack function (old ways)
- Another callback.
- Promises (better one)
- New Promise (returning promise)
- .then() >> then can be chained together.
- ex) p1.then(()=>p2).then(()=>p3)
- New Promise (returning promise)
- callBack function (old ways)
- Possible Problems
- Promise
- ex) promise.all([p1, p2, p3]).then(()=>alert(‘all promise all done!’));
- Resolve it at once. (Resolve in the order)
- Promise.all doesn’t guarantees the order
- Good with Network calls
- ex) promise.all([p1, p2, p3]).then(()=>alert(‘all promise all done!’));
- Async Await (Another way of Promise)
- Look alike synchronous codes
- Async keyword in the function
- Returns the promise
- Instead of then use await.
- Async is you can do the task as fast as possible.
- Await defines Promises
- Await blocks it
- Wait until the job is done.
- Wait until the job is done.
- Await promise.all (**array of objects)
- ex( const retVal = await Promise.all( **array))
- ex( const retVal = await Promise.all( **array))
- .catch
- Async await and catch to reject the Promise.