Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
/* Creating a Promise */ const myPromise = new Promise((resolve, reject) => { let success = true; // Change to false to test rejection setTimeout(() => { success ? resolve('Promise Resolved!') : reject('Promise Rejected!'); }, 1000); }); myPromise .then(result => console.log(result)) .catch(error => console.error(error)) .finally(() => console.log('Promise Completed')); /* Chaining Promises */ const asyncTask = value => new Promise(resolve => setTimeout(() => resolve(value * 2), 1000)); asyncTask(5) .then(result => { console.log(result); // 10 return asyncTask(result); }) .then(result => console.log(result)) .catch(err => console.log(err)); /* Promise.all - Runs all promises in parallel, resolves when all succeed */ Promise.all([asyncTask(2), asyncTask(3), asyncTask(4)]) .then(results => console.log(results)) // [4, 6, 8] .catch(err => console.error(err)); /* Promise.race - Resolves/rejects with the first completed promise */ Promise.race([asyncTask(2), asyncTask(3), asyncTask(4)]) .then(result => console.log(result)) // First resolved value .catch(err => console.error(err)); /* Promise.allSettled - Returns all promise results (fulfilled or rejected) */ Promise.allSettled([asyncTask(2), Promise.reject('Error!'), asyncTask(4)]) .then(results => console.log(results)) // Array of {status, value/reason} /* Promise.any - Resolves with first fulfilled promise (ignores rejections) */ Promise.any([Promise.reject('Error 1'), asyncTask(3), Promise.reject('Error 2')]) .then(result => console.log(result)) // First resolved value .catch(err => console.error(err.errors)); // Only if all fail // Async/Await Syntax async function fetchData() { try { const result = await asyncTask(10); console.log(result); // 20 } catch(err) { console.error(err) } } fetchData();
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)