Languages
[Edit]
EN

JavaScript - own wait-for-result method

7 points
Created by:
Hayley-Mooney
677

In this short article, we would like to show how in JavaScript write a function that waits for the result only indicated amount of the time, breaking waiting if some exceptions occur incessantly longer than it is permitted.

That kind of logic can be useful when we wait for some remote operation that shouldn't be monitored longer if a network connection lost.

Practical example:

// ONLINE-RUNNER:browser;

const sleep = async (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
};

// Waits for result from iterationCallback function.
const wait = async (
    waitingTimeout,
    throwingTimeout,
    iterationSleep,
    iterationCallback
) => {
    let errorBarrier = Number.POSITIVE_INFINITY;
    const startTime = 0.001 * Date.now();
    while (true) {
        await sleep(1000 * iterationSleep);
        const currentTime = 0.001 * Date.now();
        if (currentTime >= errorBarrier) {
            throw new Error('Exceptions occured inside iteration callback.');
        }
        const waitingDuration = currentTime - startTime;
        if (waitingDuration >= waitingTimeout) {
            return undefined;
        }
        try {
          	const iterationResult = await iterationCallback(waitingDuration);
            if (iterationResult !== undefined) {
                return iterationResult;
            }
            errorBarrier = Number.POSITIVE_INFINITY;
        } catch (error) {
            if (Number.isFinite(errorBarrier)) {
                continue;
            }
            errorBarrier = currentTime + throwingTimeout;
        }
    }
};

// Checks if in wait() function timeout occured.
const isTimeout = (result) => result === undefined;

// Usage example:

const trueCallback = async (timeElapsed) => {
    console.log(`trueCallback called in ${timeElapsed}s`);
    return true;
};
const falseCallback = async (timeElapsed) => {
    console.log(`falseCallback called in ${timeElapsed}s`);
    return false;
};
const stringCallback = async (timeElapsed) => {
    console.log(`stringCallback called in ${timeElapsed}s`);
    return 'Some string result ...';
};
const voidCallback = async (timeElapsed) => {
    console.log(`voidCallback called in ${timeElapsed}s`);
	// without any result (similar to: return undefined)
};
const exceptionCallback = async (timeElapsed) => {
    console.log(`exceptionCallback called in ${timeElapsed}s`);
    // some operation that throws exception:
    throw new Error('Some error occured ...');
};

const printResult = (result) => {
	console.log(`  wait() result: ${result}, isTimeout: ${isTimeout(result)}\n\n`);
};

;(async () => {
  	//                    waiting is stopped imidiatelly bacouse of true result
  	const result1 = await wait(5, 2, 1, trueCallback);
    printResult(result1);

  	//                    waiting is stopped imidiatelly bacouse of false result
    const result2 = await wait(5, 2, 1, falseCallback);
    printResult(result2);
  
  	//                    waiting is stopped imidiatelly bacouse of string result
  	const result3 = await wait(5, 2, 1, stringCallback);
    printResult(result3);

  	//                    waiting is stopped after 5s bacouse of undefined result
    const result4 = await wait(5, 2, 1, voidCallback);
    printResult(result4);

  	try {
      	//                    waiting is stopped after 2s bacouse of throwed exception
        const result5 = await wait(5, 2, 1, exceptionCallback);
        printResult(result5);
    } catch(e) {
    	console.log(`  wait() exception: ${e.message}\n\n`);
    }

    // other cases

  	//                    exceptions are ignored because of Number.POSITIVE_INFINITY usage
    const result6 = await wait(5, Number.POSITIVE_INFINITY, 1, exceptionCallback);
    printResult(result6);
})();

Alternative titles

  1. JavaScript - own wait-for-response method
  2. JavaScript - waiting for result from method
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join