Unraveling Nested Promises
NodeJS promises provide a powerful mechanism for handling asynchronous operations. However, nested promises can introduce code complexity. This question delves into how to transform nested promises into a more manageable chained sequence.
Original Code Structure
The original code follows a nested approach, in which the resolution of each promise triggers a subsequent promise call:
boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken) .then(function(response) { boxViewerRequest('documents', {url: response.request.href}, 'POST') .then(function(response) { boxViewerRequest('sessions', {document_id: response.body.id}, 'POST') .then(function(response) { console.log(response); }); }); });
Chaining Promises
To chain promises, it is necessary to return the new promise from the then callback of each promise. This approach allows the chained promises to resolve sequentially.
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); });
The modified code structure ensures that the promise chain continues seamlessly, with each step passing its result to the next promise in the sequence.
Generic Pattern
This chaining pattern can be generalized 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
The above is the detailed content of How Can Nested Node.js Promises Be Transformed into a Chained Sequence?. For more information, please follow other related articles on the PHP Chinese website!