What is the proper way to create a Promise that resolves after a delay?

Prepare for the Salesforce JavaScript Developer I Certification Exam. Utilize interactive quizzes, flashcards, and detailed explanations for each question. Boost your confidence and ace your exam effortlessly!

The correct approach to create a Promise that resolves after a delay is to utilize setTimeout within the promise. This method leverages the asynchronous nature of JavaScript, allowing other code to run while waiting for the specified time to pass.

When you encapsulate setTimeout within a new Promise, it initiates a timer for the defined duration. After the timeout period elapses, the promise gets resolved, thus enabling any chained .then() methods to execute. This is a clean and efficient way to create a delay in the promise resolution process, ensuring that your code remains non-blocking while still achieving the desired functionality.

For example, the implementation could look like this:


function delay(ms) {

return new Promise(resolve => setTimeout(resolve, ms));

}

In this code snippet, the promise will resolve after the specified number of milliseconds, allowing you to use it effectively in asynchronous workflows.

Other methods, such as using a for loop or creating an interval to check a condition, are generally not suitable for implementing delays in a Promise due to their synchronous behavior or continuous checking, which can lead to inefficient code and potential performance issues. Additionally, it's important to note that promises can indeed represent asynchronous operations, so it's

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy