Go back

Aysnchronous JS and API calls

Reading resources

Codes done in class

Basic settimeout

setTimeout(() => console.log("Hello"), 3000)
console.log("Hello")

Asynchronous JS

let p = (q) => new Promise((resolve, reject) => {
    setTimeout(() => {
        if(!q) reject("Error response");
        resolve("An awaited response");
    }
    ), 100000
})

// Resolving promises with async await
async function a(){
    try {
        console.log(await p(false))
    } catch (error) {
        console.log("err: " + error)
    }
}

// resolving and rejecting promises with .then .catch
p(false)
    .then(res => console.log(res))
    .catch(err => console.log("err: " + err))
console.log("hello")

Simple fetch API request

// jsonplaceholder can be used to get api calls
fetch("https://jsonplaceholder.typicode.com/posts?_limit=10")
    .then(res => res.json())
    .then(res => res.forEach(r => {
        console.log("- " + r.title)
    }))
    .catch(err => console.log("err: " + err))

console.log("hello")