Write Asynchronous code (promises) in a synchronous manner
makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
function greeting(name) {
alert(`Hello, ${name}`);
}
function processUserInput(callback) {
const name = prompt("Please enter your name.");
callback(name);
}
processUserInput(greeting);
function doStep1(init, callback) {
const result = init + 1;
callback(result);
}
function doStep2(init, callback) {
const result = init + 2;
callback(result);
}
function doStep3(init, callback) {
const result = init + 3;
callback(result);
}
function doOperation() {
doStep1(0, (result1) => {
doStep2(result1, (result2) => {
doStep3(result2, (result3) => {
console.log(`result: ${result3}`);
});
});
});
}
doOperation();
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Events: Task 2</title> | |
<style> | |
p { | |
color: purple; | |
margin: 0.5em 0; | |
} | |
* { | |
box-sizing: border-box; | |
} | |
canvas { | |
border: 1px solid black; | |
} | |
</style> | |
<link rel="stylesheet" href="../styles.css" /> | |
</head> | |
<body> | |
<section class="preview"></section> | |
<canvas width="480" height="320" tabindex="0"> </canvas> | |
<script> | |
const canvas = document.querySelector("canvas"); | |
const ctx = canvas.getContext("2d"); | |
function drawCircle(x, y, size) { | |
ctx.fillStyle = "white"; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
ctx.beginPath(); | |
ctx.fillStyle = "black"; | |
ctx.arc(x, y, size, 0, 2 * Math.PI); | |
ctx.fill(); | |
} | |
let x = 50; | |
let y = 50; | |
const size = 30; | |
drawCircle(x, y, size); | |
// Add your code here | |
canvas.addEventListener("keydown", (e) => { | |
switch (e.key) { | |
case "w": | |
y -= 20; | |
break; | |
case "a": | |
x -= 20; | |
break; | |
case "s": | |
y += 20; | |
break; | |
case "d": | |
x += 20; | |
break; | |
} | |
drawCircle(x, y, size); | |
}); | |
</script> | |
</body> | |
</html> |
getJSON("/api/usr/profile").then(displayProfile, handleError)
/* A more Readable approach: */
getJSON("/api/usr/profile").then(displayProfile).catch(handleError)
Get the JSON containing user, then display the user's profile
Nesting hell
const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');
fetchPromise.then((response) => {
const jsonPromise = response.json();
jsonPromise.then((data) => {
console.log(data[0].name);
});
});
the elegant feature of promises is that then()
itself returns a promise, which will be completed with the result of the function passed to it. This means that we can (and certainly should) rewrite the above code like this:
const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');
fetchPromise
.then((response) => response.json())
.then((data) => {
console.log(data[0].name);
});