Home > Web Front-end > JS Tutorial > How Can I Unnest Promises for Cleaner Asynchronous JavaScript Code?

How Can I Unnest Promises for Cleaner Asynchronous JavaScript Code?

Barbara Streisand
Release: 2024-12-09 22:40:10
Original
749 people have browsed it

How Can I Unnest Promises for Cleaner Asynchronous JavaScript Code?

Chaining Promises to Remove Nested Structures

When working with asynchronous operations, promises provide a convenient way to handle callbacks and maintain code readability. However, nested promises can quickly make code complex and difficult to follow. This article discusses how to remove nested promises and chain them for improved clarity.

Approach

To remove nested promises, we return a new promise from each then callback. This allows us to chain the promises one after the other, eliminating the need for nested structures. Here's a modified version of the provided code:

exports.viewFile = function(req, res) {
    var fileId = req.params.id;
    boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
      .then(function(response) {
          return boxViewerRequest('documents', {url: response.request.href}, 'POST');
      })
      .then(function(response) {
          return boxViewerRequest('sessions', {document_id: response.body.id}, 'POST');
      })
      .then(function(response) {
          console.log(response);
      });
};
Copy after login

In this code, each then callback returns the promise for the subsequent request, ensuring that the execution continues sequentially.

General Pattern

The pattern for chaining promises is as follows:

somePromise.then(function(r1) {
    return nextPromise.then(function(r2) {
        return anyValue;
    });
}) // resolves with anyValue

     ||
    \||/
     \/

somePromise.then(function(r1) {
    return nextPromise;
}).then(function(r2) {
    return anyValue;
}) // resolves with anyValue as well
Copy after login

When returning a new promise, the resulting value from that promise is passed to the next handler in the chain. Alternatively, if the promise returned by the handler is the last one in the chain, the resolve value of that promise is passed to the consumer.

The above is the detailed content of How Can I Unnest Promises for Cleaner Asynchronous JavaScript Code?. 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