Search code examples
javascriptes6-promise

Unexpected Resolve is not a function


I have this function and I want to await for it like this:

await triesPlay(blobSource, reference);

But unexpectedly it returns an error when reaching triesPlayResolve(); inside this if statment:

if(consecutive(exist)) {
   report.consecutiveTried.push([reference, c]);
   triesPlayResolve(); // reaching this produces the error
   return;
}

Here is the error:

enter image description here

And Here is the function:

function triesPlay(blobSource, reference) {
    let triesPlayResolve;
    int();
    async function int() {
        for(let c = 0; c < options.maxTry; c++) {
            if(consecutive(exist)) {
                report.consecutiveTried.push([reference, c]);
                triesPlayResolve();
                return;
            }
            await proccess();
            function proccess() {
                let proccessResolve;
                int();
                async function int() {
                    await Recognize(blobSource);
                    if(speechResult.simplify() === '') {
                        int();
                        return;
                    }
                    saveExpect(speechResult.simplify(), reference);
                    primaryExpects.push(speechResult.simplify());
                    proccessResolve();
                }
                return new Promise(resolve => { 
                    proccessResolve = resolve;
                });
            }
        }
        report.maxTried.push(reference);
        triesPlayResolve();
    }
    return new Promise(resolve => { 
        triesPlayResolve = resolve;
    });
}

It dosn't make any sense for me!! how can I fix this? and why this is happening?!


Solution

  • You are calling the function before your new Promise instantiation at the end of the function initialises the variable.

    But all of this is totally unnecessary - async functions work that way out of the box, they always return an implicit promise that is resolved when the code in the function body returns, even (or: especially) after an await. You don't need any of those internal helper functions.

    So you can simplify to

    async function triesPlay(blobSource, reference) { /*
    ^^^^^ */
        for (let c = 0; c < options.maxTry; c++) {
            if (consecutive(exist)) {
                report.consecutiveTried.push([reference, c]);
                return;
    //          ^^^^^^^ this is enough!
            }
    
            while (speechResult.simplify() === '') {
                await Recognize(blobSource);
            }
            saveExpect(speechResult.simplify(), reference);
            primaryExpects.push(speechResult.simplify());
        }
        report.maxTried.push(reference);
    }