This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
The keyword
before a function makes the function return a promise:async function myFunction() {
return "Hello";
}
Is the same as:
function myFunction() {
return Promise.resolve("Hello");
}
Here is how to use the Promise:
myFunction().then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
async function myFunction() { return "Hello"; } myFunction().then( function(value) {myDisplayer(value);}, function(error) {myDisplayer(error);} );
Or simpler, since you expect a normal value (a normal response, not an error):
async function myFunction() { return "Hello"; } myFunction().then( function(value) {myDisplayer(value);} );
let value = await promise;
Let's go slowly and learn how to use it.
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I love You !!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
async function getFile() {
let myPromise = new Promise(function(resolve) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
resolve("File not Found");
}
};
req.send();
});
document.getElementById("demo").innerHTML = await myPromise;
}
getFile();
Chrome 55 | Edge 15 | Firefox 52 | Safari 11 | Opera 42 |
Dec, 2016 | Apr, 2017 | Mar, 2017 | Sep, 2017 | Dec, 2016 |
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon