Home >Web Front-end >JS Tutorial >Why does using setTimeout() inside a promise chain lead to a JSON parsing error?

Why does using setTimeout() inside a promise chain lead to a JSON parsing error?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 12:53:29679browse

Why does using setTimeout() inside a promise chain lead to a JSON parsing error?

Using setTimeout() in Promise Chains

When working with promises, it's important to understand how to properly handle asynchronous operations. One common issue is attempting to use setTimeout() within a promise chain.

In the provided code snippet, the goal is to fetch a set of links and then fetch the content of the first link. However, a setTimeout() call is used to introduce a delay before returning the next promise object. This leads to a JSON parsing error.

Why does it fail?

Using setTimeout() outside of a promise chain prevents the promise chain from continuing. In this case, the setTimeout() callback is returning a promise, but it's not being chained to the previous promise. Consequently, the subsequent chain operations are not being executed.

Solution

To keep the promise chain intact, you must return the promise from the .then() handler. The setTimeout() function should be wrapped in a new promise, ensuring that the promise chain is maintained.

Example

Replace the setTimeout() call with the following code:

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

The delay function wraps the setTimeout() call in a promise, allowing it to be chained to the previous promise.

Alternatively, you can extend the Promise object with a delay method:

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

This allows you to use .delay(x) directly on promises:

<code class="js">getLinks('links.txt')
   .then((links) => {
      return getLinks(globalObj["one"] + ".txt");
   })
   .then((topic) => {
      return Promise.resolve(topic).delay(1000);
   })
   .then((topic) => {
      return getLinks(globalObj["two"] + ".txt");
   });</code>

The above is the detailed content of Why does using setTimeout() inside a promise chain lead to a JSON parsing error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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