jadjoubran / codetogo.io

🚀 JavaScript code to go - Find updated snippets for common JavaScript use cases
https://codetogo.io
MIT License
231 stars 30 forks source link

New use cases #163

Closed jadjoubran closed 4 years ago

jadjoubran commented 5 years ago
jadjoubran commented 5 years ago
Darth-koder007 commented 5 years ago

@jadjoubran I can go ahead an implement an example for these and raise a PR for the same.

jadjoubran commented 5 years ago

Thanks @Darth-koder007 Yes feel free! Let's do it one by one though and it would be great if you can share the code snippet in a comment here first to maintain consistency

Darth-koder007 commented 5 years ago

@jadjoubran Sharing the snippet for Async/Await (Use try/catch for error handling) Have a look and provide feedback

/**
 * @description Returns a promise in either fulfilled
 * or rejected state after sometime
 *
 * @param {boolean} [shouldResolve=true] shouldResolve
 * @param {number} [afterTime=2000] afterTime
 *
 * @return {Promise}
 */
function promiseReturn(shouldResolve = true, afterTime = 2000) {
    return new Promise((resolve, reject) => {
        window.setTimeout(() => {
            if (shouldResolve) resolve("Promise resolved");
            reject("Promise rejected");
        }, afterTime);
    });
}

/**
 * @description Driver function for resolving or rejecting
 * a promise after provided time
 *
 * @param {boolean} shouldResolve
 * @param {boolean} afterTime
 *
 * @return {void}
 */
async function resolveOrRejectPromise(shouldResolve, afterTime) {
    let promiseMessage = "";
    try {
        promiseMessage = await promiseReturn(shouldResolve, afterTime);
    } catch (e) {
        promiseMessage = e;
    }

    alert(promiseMessage);
}

// Rejects the promise after 2000ms
resolveOrRejectPromise(false, 2000);

// Fulfils the promise after 3000ms
resolveOrRejectPromise(true, 3000);
Darth-koder007 commented 5 years ago

@jadjoubran sharing snippet for use case cancel timeout

let timeOutID = window.setTimeout(() => {
    console.log('I will not be printed');
}, 2000);
window.clearTimeout(timeOutID);
Darth-koder007 commented 5 years ago

@jadjoubran sharing snippet for use case cancel interval

let intervalID = window.setInterval(() => {
    console.log('I will not be printed');
}, 2000);
window.clearInterval(intervalID);
Darth-koder007 commented 5 years ago

@jadjoubran Please have a look

jadjoubran commented 5 years ago

Thanks @Darth-koder007, sorry got busy in the last month The clearInterval and clearTimeout look good 👍 can you please submit them as a PR? It would be great if you can use const rather than let to align with the other use case the async/await example is way too big for codetogo as most of the usecases here are under 5 lines long. Maybe it makes sense to use async/await on a function that returns a promise, such as fetch?

Darth-koder007 commented 5 years ago

@jadjoubran How's this for async/await example ?

(async () => {
  let anon = await fetch('/');
  console.log(await anon.text())
})();
jadjoubran commented 5 years ago

Thanks @Darth-koder007 Can you please use this example and make it into an async/await call? https://codetogo.io/how-to-fetch-json-in-javascript/ It's also probably a good idea to wrap it in a try/catch so that users remember to handle errors

Darth-koder007 commented 5 years ago

@jadjoubran I have incorporated your suggestion Please have a look

(async () => {
    try {
       const fetchResponse = await fetch("https://codetogo.io/api/users.json");
       console.log(await fetchResponse.json());
    } catch(err){
       console.error(err);
    }
})();
jadjoubran commented 5 years ago

Thanks a lot @Darth-koder007! Can you please go with this one instead?

(async () => {
    try {
       const response = await fetch("https://codetogo.io/api/users.json");
       const data = await response.json();
       console.log(data);
    } catch(err){
       console.error(err);
    }
})();

I just renamed a variable and added another one to make it clearer You can use the fetch-json.md as a template as it already contains the output

jadjoubran commented 4 years ago

🎬 How to async/await fetch in JavaScript