Home > Web Front-end > JS Tutorial > body text

How to Properly Incorporate setTimeout() into Promise Chains?

Susan Sarandon
Release: 2024-10-31 16:02:02
Original
534 people have browsed it

How to Properly Incorporate setTimeout() into Promise Chains?

Using setTimeout() in Promise Chains

When working with promises, it's essential to understand how to handle asynchronous operations within a promise chain. In the given code snippet, the intention is to delay the execution of a subsequent request in a promise chain. However, using setTimeout() directly within the .then() handler can lead to issues.

Why setTimeout() Fails

In your code, setTimeout() is used within the .then() handler of the second request. However, this approach breaks the promise chain because the returned value of the .then() handler is not a promise. The setTimeout() callback, which contains the promise you want to chain, is not accessible outside its own context.

Solution Using delay Function

To maintain the promise chain, you can create a separate delay function that returns a promise:

<code class="javascript">function delay(t, val) {
    return new Promise(resolve => setTimeout(resolve, t, val));
}</code>
Copy after login

Then, use the delay function in your promise chain:

<code class="javascript">return delay(1000).then(function() {
    return getLinks(globalObj["two"] + ".txt");
});</code>
Copy after login

This returns a promise from the .then() handler, which ensures that the execution of the subsequent request is delayed.

Alternative Using Promise.prototype.delay

Another option is to extend the Promise object with a delay method:

<code class="javascript">Promise.prototype.delay = function(t) {
    return this.then(function(val) {
        return delay(t, val);
    });
}</code>
Copy after login

With this method, you can directly call .delay() on your promises:

<code class="javascript">Promise.resolve("hello").delay(500).then(function(val) {
    console.log(val);
});</code>
Copy after login

Both approaches ensure that the promise chain is maintained correctly and the subsequent request is executed after the specified delay.

The above is the detailed content of How to Properly Incorporate setTimeout() into Promise Chains?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!