JavaScript Promises
JavaScript Promises
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT
JavaScript Promises
❮ Previous Next ❯
Promise Syntax
When the producing code obtains the result, it should call one of the two callbacks:
When Call
Pending
Fulfilled
Rejected
The Promise object supports two properties: state and result.
Tutorials Exercises Services Spaces Get Certified My W3Schools
While a Promise object is "pending" (working), the result is undefined.
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT
When a Promise object is "fulfilled", the result is a value.
myPromise.state myPromise.result
"pending" undefined
Promise How To
Here is how to use a Promise:
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Promise.then() takes two arguments, a callback for success and another for failure.
Both are optional, so you can add a callback for success or failure only.
Example
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Try it Yourself »
Tutorials Exercises Services Spaces Get Certified My W3Schools
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
Try it Yourself »
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Try it Yourself »
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(req.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
Tutorials Exercises Services Spaces Get Certified My W3Schools
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT
Try it Yourself »
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Try it Yourself »
Browser Support
ECMAScript 2015, also known as ES6, introduced the JavaScript Promise object.
The following table defines the first browser version with full support for Promise objects:
Feb, 2014 Jul, 2015 Apr, 2014 Sep, 2014 Mar, 2014
❮ Previous Next ❯
Tutorials Exercises Services Spaces Get Certified My W3Schools
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT
CONTACT US
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT