• About
  • Privacy Policy
  • Disclaimer
  • Contact
Soft Bliss Academy
No Result
View All Result
  • Home
  • Artificial Intelligence
  • Software Development
  • Machine Learning
  • Research & Academia
  • Startups
  • Home
  • Artificial Intelligence
  • Software Development
  • Machine Learning
  • Research & Academia
  • Startups
Soft Bliss Academy
No Result
View All Result
Home Software Development

How to Set Timeout for a JavaScript Promises

softbliss by softbliss
May 28, 2025
in Software Development
0
How to Set Timeout for a JavaScript Promises
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter


How to Set Timeout for a JavaScript Promises

JavaScript promises are a powerful tool for handling asynchronous code execution. They allow us to write cleaner and more maintainable code by making it easier to handle async operations. However, there are times when we want to set a timeout for a promise to make sure it doesn’t take too long to resolve or reject. In this article, we will explore different approaches to setting a timeout for a JavaScript promise and discuss the pros and cons of each.

Approach 1: Using Promise.race

One way to set a timeout for a promise is by using the Promise.race method. This method takes an array of promises and returns a new promise that is settled as soon as any of the input promises are settled. We can leverage this behavior to create a timeout mechanism. Here’s an example: 


function timeoutPromise(promise, timeout) {
    const timeoutPromise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                reject(new Error('Promise timed out'))
            }, timeout)
        }
    );

    return Promise.race([promise, timeoutPromise]);
}

// Usage
const promise = new Promise((resolve, reject) => {
    // some async operation
});

const timeout = 5000; // 5 seconds
const result = await timeoutPromise(promise, timeout);

In this example, we create a new promise called timeoutPromise that rejects after the specified timeout. We then use Promise.race to return a new promise that settles either with the result of the original promise or with a timeout error, whichever occurs first.

Approach 2: Using async/await and setTimeout

Another approach is to leverage the power of async/await syntax along with setTimeout to create a timeout mechanism for a promise. 


function timeoutPromise(promise, timeout) {
    return new Promise(
        async (resolve, reject) => {
            const timeoutId = setTimeout(() => {
                clearTimeout(timeoutId);
                reject(new Error('Promise timed out'));
            }, timeout);

            try {
                const result = await promise;
                clearTimeout(timeoutId);
                resolve(result);
            }
            catch (error) {
                clearTimeout(timeoutId);
                reject(error);
            }
        }
    );
}

// Usage
const promise = new Promise((resolve, reject) => {
    // some async operation
});

const timeout = 5000; // 5 seconds
const result = await timeoutPromise(promise, timeout);

Here, we create a new promise that wraps the original promise. We use async/await to handle the asynchronous nature of the original promise. We start a timer using setTimeout, and if the timer expires before the original promise resolves or rejects, we reject the new promise with a timeout error. Otherwise, we clear the timer and resolve or reject the new promise based on the outcome of the original promise. 

Both of these approaches achieve the goal of setting a timeout for a JavaScript promise. However, they differ in how they handle the timeout mechanism. In approach 1 we use a Promise.race to race the original promise with a timeout promise, while approach 2 uses setTimeout along with async/await to create a more integrated and readable solution.

It’s important to note that setting a timeout for a promise is not a guarantee that the underlying async operation will be canceled. It only ensures that the promise itself will settle within the specified timeout.

If necessary, you should handle the cleanup of any resources associated with the async operation separately.

Conclusion

Setting a timeout for a JavaScript promise can be achieved using different approaches. The choice depends on the requirements and style preferences of the project. Regardless of the approach you choose, adding a timeout to promises can greatly enhance the robustness and reliability of your asynchronous code.

Tags: JavaScriptPromisesSetTimeout
Previous Post

Mistral Launches Agents API: A New Platform for Developer-Friendly AI Agent Creation

Next Post

Google’s Project Green Light AI traffic reduction initiative expands in Boston

softbliss

softbliss

Related Posts

Forest And Desert
Software Development

Forest And Desert

by softbliss
May 29, 2025
Salesforce Development Services for Scalable Digital Transformation 
Software Development

Salesforce Development Services for Scalable Digital Transformation 

by softbliss
May 28, 2025
How to find the most reliable flutter app development company?
Software Development

How to find the most reliable flutter app development company?

by softbliss
May 27, 2025
How It’s Made: Little Language Lessons uses Gemini’s multilingual capabilities to personalize language learning
Software Development

Gemini API I/O updates – Google Developers Blog

by softbliss
May 27, 2025
Crypto Sniper Bot Development: Trading Bot Guide
Software Development

Crypto Sniper Bot Development: Trading Bot Guide

by softbliss
May 26, 2025
Next Post
Google’s Project Green Light AI traffic reduction initiative expands in Boston

Google’s Project Green Light AI traffic reduction initiative expands in Boston

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Premium Content

MM-Ego: Towards Building Egocentric Multimodal LLMs

April 12, 2025
How can India decarbonize its coal-dependent electric power system? | MIT News

How can India decarbonize its coal-dependent electric power system? | MIT News

May 7, 2025
Fixing Cumulative Layout Shift Problems on DavidWalshBlog

Fixing Cumulative Layout Shift Problems on DavidWalshBlog

May 25, 2025

Browse by Category

  • Artificial Intelligence
  • Machine Learning
  • Research & Academia
  • Software Development
  • Startups

Browse by Tags

Amazon App Artificial BigML.com Blog Build Building Business Data Development Digital Future Gemini Generative Google Guide Impact Innovation Intelligence Key Language Large Learning LLM LLMs Machine Microsoft MIT model Models News NVIDIA Official opinion OReilly Research Science Series Software Startup Startups students Tech Tools Video

Soft Bliss Academy

Welcome to SoftBliss Academy, your go-to source for the latest news, insights, and resources on Artificial Intelligence (AI), Software Development, Machine Learning, Startups, and Research & Academia. We are passionate about exploring the ever-evolving world of technology and providing valuable content for developers, AI enthusiasts, entrepreneurs, and anyone interested in the future of innovation.

Categories

  • Artificial Intelligence
  • Machine Learning
  • Research & Academia
  • Software Development
  • Startups

Recent Posts

  • Integrating AI Girlfriend Chatbots into Daily Life: Benefits and Drawbacks
  • Foundation Model Hidden Representations for Heart Rate Estimation from Auscultation
  • Degrees and Skills: A More Promising Approach

© 2025 https://softblissacademy.online/- All Rights Reserved

No Result
View All Result
  • Home
  • Artificial Intelligence
  • Software Development
  • Machine Learning
  • Research & Academia
  • Startups

© 2025 https://softblissacademy.online/- All Rights Reserved

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?