乐闻世界logo
搜索文章和话题

Promises , pass additional parameters to then chain

1个答案

1

In JavaScript, Promise is a mechanism for handling asynchronous operations. The then() method is part of the Promise object and is used to specify callback functions that execute when the Promise is fulfilled or rejected. If you wish to pass additional parameters within the then chain, several approaches can be employed:

1. Using Closures

Closures allow inner functions to access variables from the outer function's scope, making it easy to pass parameters within the then chain.

javascript
function getData() { let additionalParam = 'example'; return fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { return { data, additionalParam }; }); } getData().then(result => { console.log(result.data); // Data from API console.log(result.additionalParam); // 'example' });

In this example, we pass additional parameters by returning an object containing data and additionalParam.

2. Using Arrow Functions

Arrow functions capture the this value from their context, enabling access to variables from the enclosing scope.

javascript
let additionalParam = 'example'; function getData() { return fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { return { data, additionalParam }; }); } getData().then(result => { console.log(result.data); // Data from API console.log(result.additionalParam); // 'example' });

3. Passing Parameters at Each Step

If your parameters need to be passed step-by-step within the then chain, you can return them in each then.

javascript
function getData(param) { return fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { return { data, param }; }) .then(result => { console.log(result.param); // Print additional parameter return result.data; }); } getData('example').then(data => { console.log(data); // Data from API });

4. Using Global Variables or External Storage

Although using global variables to pass parameters is not recommended (as it can lead to unpredictable and hard-to-maintain code), it may be a viable solution in certain cases if handled properly.

javascript
let additionalParam = 'example'; function getData() { return fetch('https://api.example.com/data') .then(response => response.json()); } getData().then(data => { console.log(data); // Data from API console.log(additionalParam); // 'example', retrieved from global variable });

In summary, the recommended approach is to pass additional parameters through closures and function scope, as this avoids side effects from global variables while maintaining modular and clear code.

2024年7月1日 17:56 回复

你的答案