mardi 9 juin 2020

Is there a way to access an object values from an if statement without being declared globally?

I apologize beforehand for the Title of the questions. I know it sounds weird but english is not my first language, again apologies.I cant translate my doubt title any better.

Let´s me explain myself a little better. Lest say we have:

    let foo,bar;

and because im using async/await i follow the patter of:

    const asynk_bar = async (Promise) => {
    let foo, bar;
    [foo, bar] = await asynk_bar(Promise);
    if (foo) return [foo,null];
    return [null,bar];
    }

    const asynk_main=async() =>{
        let foo,bar;
        [foo,bar] = await async_bar(arg);   //arg = async function i want to use 
        if(bar!=null){
            // =>  More nested patterns of let foo2,bar2; ...
        }else{
            throw new Error("Whoops!");
        }
    }

Which i think works fine , but all of those nested ifs are kinda messy... And i was wondering, if i could reduce the amount of code to something like:

    const asynk_main=async() =>{
         //arg = async function i want to use to get some values
        if(await async_bar(arg)!=null){
            ...
                //later on   use the value retuned from the Promise
        }throw new Error("Whoops!");  
    }

Is there a way to achieve this?

Maybe im not seeing my fault in my logic.

Any suggestions are welcome and please share your patterns for await/ async hell.

Probably better than mine :P

Aucun commentaire:

Enregistrer un commentaire