Home >Web Front-end >JS Tutorial >Why Does Using `setTimeout` in a Promise Chain Cause a JSON Parsing Error?

Why Does Using `setTimeout` in a Promise Chain Cause a JSON Parsing Error?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 05:49:28483browse

Why Does Using `setTimeout` in a Promise Chain Cause a JSON Parsing Error?

Using setTimeout on Promise Chain

In an attempt to explore promises, you've attempted to fetch a set of links using an initial request and fetch the content of the first link using a subsequent request. To introduce a delay before returning the next promise object, you've employed setTimeout. However, this approach encounters a JSON parsing error that vanishes when setTimeout() is eliminated.

To elucidate this error, it's crucial to understand that to maintain the continuity of the promise chain, you cannot utilize setTimeout() as you did. The reason being, you're not returning a promise from the .then() handler, but rather from the setTimeout() callback, which renders your efforts ineffective.

Instead, consider implementing a simple delay function:

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

With this delay function in place, you can modify your code as follows:

<code class="js">getLinks('links.txt').then(function(links){
    let all_links = (JSON.parse(links));
    globalObj=all_links;

    return getLinks(globalObj["one"]+".txt");

}).then(function(topic){
    writeToBody(topic);
    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");
    });
});</code>

This modification ensures that you're returning a promise from the .then() handler, thereby chaining it appropriately.

Alternatively, you can extend the Promise object with a delay method, allowing you to employ a more concise syntax:

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

Promise.resolve("hello").delay(500).then(function(val) {
    console.log(val);
});</code>

By incorporating these modifications, you can seamlessly introduce delays within your promise chain, alleviating the encountered JSON parsing error.

The above is the detailed content of Why Does Using `setTimeout` in a Promise Chain Cause 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