<html> <head> <metacharset="utf-8"> <title>JavaScript - Async - Level 2 - Promises</title> <metaname="viewport"content="width=device-width, initial-scale=1"> <metaname="description"content="JavaScript - Async - Level 2 - Promises"> </head> <body> <h1>JavaScript - Async - Level 2 - Promises</h1> <script> // Run JavaScript after the DOM is fully loaded document.addEventListener('DOMContentLoaded', function () { console.log('DOM fully loaded and parsed.'); // Your script logic here console.log('Start'); console.log('3'); wait(1000) .then(() => { console.log('2'); returnwait(1000); }) .then(() => { console.log('1'); returnwait(1000); }) .then(() => { console.log('Happy New Year!!'); }); // end of event listener }); functionwait(duration) { returnnewPromise((resolve) => { setTimeout( () =>resolve(), duration ); }); } </script> </body> </html>
Promises introduce the concept of chaining, infact the example above shows chaining multiple promises.
Promises terminology
Promises are always in one of three possible states: pending, fulfilled, and rejected.
Creating your own promise
Here is an example of creating your own promise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
functiongetUser(userId) { returnnewPromise((resolve) => { // The asynchronous work, in this case, is // looking up a user from their ID db.get({ id: userId }, (user) => { // Now that we have the full user object, // we can pass it in here... resolve(user); }); }); }
getUser('abc123').then((user) => { // ...and pluck it out here! console.log(user); // { name: 'Josh', ... } })
the Response object.
If the code runs to completion it returns a positive object, But there could be an error.