new Promise((resolve, reject) => { resolve(value) reject(error)})
The modern way of API call / fetch API, uses promises to resolve or reject based on the API response.
We can use API’s to get access to third party resources like weather, temperature etc.
We can use two methods to handle API requests async...await functions and .then().then()...catch()
The fetch api used to call APIs from JS uses promises udnerneat.
The setTimeout() method uses a callback function (a function which is called back from the setTimeout, after the set time) to return an asynchronous, delayed output.
callback functions are functions which accept another function and calls it from the body of the function.
let p = (q) => new Promise((resolve, reject) => { setTimeout(() => { if(!q) reject("Error response"); resolve("An awaited response"); } ), 100000})// Resolving promises with async awaitasync function a(){ try { console.log(await p(false)) } catch (error) { console.log("err: " + error) }}// resolving and rejecting promises with .then .catchp(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 callsfetch("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")