JSFiddle - React, Tailwind, and code Playground

by jrab227

JavaScript 1.7

async function testNTimesUntilOk(func, n, lastFail) {

    let _tries = 1;
		if (!isNaN(n)) {
    		_tries = n;
    }

		if (_tries > 5) return Promise.reject(lastFail);

		let result;
		try {
    		result = await func();
    } catch (e) {
    		return testNTimesUntilOk(func, _tries + 1, e);
    }
    return result;
    
  
}

function Testable() {
		this.tries = 0;
    this.run = () => {
        console.log("Running " + this.tries)
    		if (this.tries > 3) return Promise.resolve({});
        this.tries += 1;
        return Promise.reject("Failed");
    }
}

let myAsyncTest = new Testable();

Promise.resolve({}).then(() =>
	testNTimesUntilOk(() => myAsyncTest.run())
)
.then(() => console.log("Ok"))
.catch((e)=> console.log(e))