async vs promise


    /////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////// Async ////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
    // const promise = fetch('https://jsonplaceholder.typicode.com/todos')
    // promise
    //     .then(res => res.json())        
    //     .then(data => console.log(data))
    //     .catch(err => console.log(err))

    const getBlogs = async (name) => {
        const fruits = {
            "one": "One 1",
            "two": "Two 2",
            "three": "Three 3"
        }
        await delay(2000);
        return Promise.resolve(fruits[name]);
    }

    // for small
    const makeMe = async () => {
        try {
            let a = getBlogs('one');
            let b = getBlogs('two');
            const final = Promise.all([a, b]);
            //    throw "error";
            return final;
        } catch (err) {
            console.log(err);
            return "we are going to fine";
            // throw "Its broken"
        }
    }
    makeMe()
        .then(v => console.log(v))
        .catch(error => { console.log(error) })

    // For Multiple
    const datas = ['one', 'two', 'three', 'one', 'two', 'three'];
    const getDatas = async () => {
        let temp = [];        
        for await (const v of datas) {
            let a = getBlogs(v);
            temp.push(a);
        }
        // Resolving all Promise in short 
        return Promise.all(temp);
    }
    getDatas().then(val => {
        console.log(val);
    });

    
    /////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////// Promise ////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
    const testFun = (data) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (data == 1) {
                    resolve('i');
                } else {
                    reject('r');
                }
            }, 5000)
        })
    }

    testFun(2).then(val => console.log(val))
        .catch(err => console.log(err));

Comments

Popular posts from this blog

Module Bundel

Power of async and Promise