Home > Article > Web Front-end > 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>
Then, use the delay function in your promise chain:
<code class="javascript">return delay(1000).then(function() { return getLinks(globalObj["two"] + ".txt"); });</code>
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>
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>
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!