Hướng dẫn recursive api call javascript - đệ quy api gọi javascript

3 cách để thực hiện các yêu cầu HTTP đệ quy với các cuộc gọi lại, lời hứa và async/đang chờ đợi.

Yêu cầu HTTP đệ quy với các cuộc gọi lại, lời hứa, & async/chờ đợi

Kịch bản

Điều này sẽ giúp bạn nếu để bạn thực hiện một nhiệm vụ bạn cần thu thập một loạt thông tin theo một thứ tự cụ thể. Một kịch bản khác là bạn cần tự động hóa một loạt các yêu cầu theo một chuỗi cụ thể. Tôi sẽ bao gồm ba cách để làm điều này trong một chức năng đệ quy.

Và vâng, tôi biết có thể có một cách hiệu quả hơn để thực hiện graphQL này nhưng điều đó có thể không giải quyết được nhiều truy vấn cho nhiều API.

API

Đối với hướng dẫn này, chúng tôi sẽ sử dụng https://jsonplaceholder.typicode.com làm phương tiện của chúng tôi để lấy dữ liệu.

JsonPlaceholder.Typicode.com

Kịch bản mà chúng tôi sẽ thử và giải quyết là thực hiện 3 yêu cầu và truy xuất TODO ____10,

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
1 và
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
2, theo thứ tự tuần tự.

Điều này chủ yếu cho các mục đích minh họa, nhưng trong một kịch bản thực tế hơn, chúng tôi có thể tìm nạp dữ liệu từ phần phụ trợ của mình để lấy địa chỉ, sau đó gửi yêu cầu đó đến Google Map dữ liệu.

Gọi lại đệ quy

Gọi lại là cách ban đầu để thực hiện tuần tự các yêu cầu. Đối với điều này, tôi sẽ tránh các chức năng trả lại những lời hứa như

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
3 và gắn bó với
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
4 ban đầu.

Xác định yêu cầu XHR HTTP của chúng tôi

const xhr = new XMLHttpRequest();xhr.addEventListener('load', (data) => {
console.log(data.currentTarget.response); // json data
console.log(data.currentTarget.status); // status code
});
xhr.addEventListener('error', (error) => {
// default error handler, ex URL doesn't exist
// Not to be confused with 404 which is still a success
console.log('Something went wrong.');
});
xhr.open('get', 'https://jsonplaceholder.typicode.com/todos/1');xhr.send();

Yêu cầu gói trong hàm đệ quy

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);

Điều này sẽ hoạt động đúng? Vâng, nếu chúng ta chạy nó, đầu ra là:

undefined

Tại sao điều này? Đó là vì yêu cầu HTTP của chúng tôi đã hoàn thành và chúng tôi đã đưa ra kết quả trước khi mọi thứ kết thúc.

Mã gọi lại đệ quy cuối cùng Mã yêu cầu HTTP

Sau đó, chúng ta cần thay đổi mọi thứ để làm cho nó để chúng ta vượt qua chức năng

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
5 để cho chức năng đệ quy của chúng ta biết những gì cần gọi khi nó thực hiện.

// Revised Recursive Function
const reqs = (requests = [], store = [], callback, failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();

// move on to next request
return reqs(requests, store, callback, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});
xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
if (callback) {
callback(store);
}

}
};

// Init
reqs([
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/1'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/3'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/7'
}

],
[],
(data) => console.log(data), // Output results
(error) => console.log(error)
);

Bây giờ khi chúng tôi chạy nó, chúng tôi sẽ nhận được đầu ra sau:

[
{"userId":1,"id":1,"title":"delectus aut autem","completed":false},{"userId":1,"id":3,"title":"fugiat veniam minus","completed":false},{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}
]

Hứa hẹn đệ quy

Với những lời hứa đệ quy, chúng ta có thể tận dụng việc sử dụng tìm nạp. Một giới hạn cần lưu ý với Fetch là chúng tôi không thể có được tiến trình tải xuống, vì vậy nếu chúng tôi muốn tiến hành lấy dữ liệu, chúng tôi sẽ không thể thực hiện và trong kịch bản đó, tôi sẽ chỉ sử dụng

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
6 và bọc nó trong một
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
7 .

Xác định yêu cầu HTTP tìm nạp của chúng tôi

const config = {
method: 'get'
};
fetch('https://jsonplaceholder.typicode.com/todos/1', config)
.then(response => {
const json = response.json();
if (response.ok) {
return json;
}
return json.then(data => new Promise.reject(data));
})
.then(jsonData => {
console.log(jsonData);
})
.catch(error => console.log(error));

Mã yêu cầu HTTP hứa hẹn cuối cùng

// Promise Recursive Function 
const reqsPromises = (requests = [], data = []) => new Promise((resolve, reject) => {
if (requests instanceof Array && requests.length > 0) {
const config = {
method: requests[0].method
};

return fetch(requests[0].url, config)
.then(response => {
const json = response.json();
if (response.ok) {
return json;
}
return json.then(data => reject(data));
})
.then(jsonData => resolve(reqsPromises(requests.slice(1), [ ...data, ...[jsonData] ])));
}
return resolve(data);
});

// Init
reqsPromises([
{
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'get'
},
{
url: 'https://jsonplaceholder.typicode.com/todos/3',
method: 'get'
},
{
url: 'https://jsonplaceholder.typicode.com/todos/7',
method: 'get'
}
],
[]
)
.then(data => console.log(data)) // Output results
.catch(error => console.log(error));

Async đang chờ đệ quy

Điều cần nhớ với

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
8 là nó vẫn mong đợi một
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
9 và may mắn là
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
3 đã là một lời hứa. Điều chính cần nhớ là
undefined
1 về cơ bản đang biến một hàm chính quy thành
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
9.

Basically:

const myPromise = () => new Promise.resolve('hello');// = the same as const myAsync = async () => 'hello';

Xác định yêu cầu HTTP Async đang chờ đợi của chúng tôi

Chúng tôi kết thúc yêu cầu

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
3 của chúng tôi trong một
undefined
4 và
undefined
5 hoạt động giống như
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
9
undefined
5 và chúng tôi
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
8
// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
3 bởi vì nó đã là một lời hứa và khi chúng tôi nhận được phản hồi, chúng tôi chuyển đổi chức năng không hứa hẹn của mình thành một lời hứa với
// Revised Recursive Function
const reqs = (requests = [], store = [], callback, failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();

// move on to next request
return reqs(requests, store, callback, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});
xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
if (callback) {
callback(store);
}

}
};

// Init
reqs([
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/1'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/3'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/7'
}

],
[],
(data) => console.log(data), // Output results
(error) => console.log(error)
);

0.

________số 8

Bạn cũng sẽ nhận thấy có thêm

// Recursive Function
const reqs = (requests = [], store = [], failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();
// move on to next request
return reqs(requests, store, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});

xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
return store;
}
};

// Init
const results = reqs([{method: 'get', url: 'https://jsonplaceholder.typicode.com/todos/1'}], [], (error) => console.log(error));
// Output Results
console.log(results);
8 trên
// Revised Recursive Function
const reqs = (requests = [], store = [], callback, failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();

// move on to next request
return reqs(requests, store, callback, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});
xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
if (callback) {
callback(store);
}

}
};

// Init
reqs([
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/1'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/3'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/7'
}

],
[],
(data) => console.log(data), // Output results
(error) => console.log(error)
);

2 đó là do
// Revised Recursive Function
const reqs = (requests = [], store = [], callback, failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();

// move on to next request
return reqs(requests, store, callback, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});
xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
if (callback) {
callback(store);
}

}
};

// Init
reqs([
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/1'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/3'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/7'
}

],
[],
(data) => console.log(data), // Output results
(error) => console.log(error)
);

3 =
// Revised Recursive Function
const reqs = (requests = [], store = [], callback, failback) => {
// Check if there are still requests to make
if (requests instanceof Array && requests.length > 0) {
const xhr = new XMLHttpRequest();

// Success handling
xhr.addEventListener('load', (data) => {
const status = data.currentTarget.status;
const response = data.currentTarget.response;
if (status === 200) {;
// add to store
store.push(JSON.parse(response));

// remove first request from array of requests
requests.shift();

// move on to next request
return reqs(requests, store, callback, failback);
} else {
if (failback) {
failback(`Request Error: ${status}`);
}
}
});

// Failure handling
xhr.addEventListener('error', (error) => {
if (failback) {
failback('Something went wrong.');
}
});
xhr.open(requests[0].method, requests[0].url);

xhr.send();
} else {
if (callback) {
callback(store);
}

}
};

// Init
reqs([
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/1'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/3'
},
{
method: 'get',
url: '
https://jsonplaceholder.typicode.com/todos/7'
}

],
[],
(data) => console.log(data), // Output results
(error) => console.log(error)
);

2 cũng là một lời hứa.

Async đệ quy cuối cùng đang chờ mã yêu cầu HTTP

// Async Await Recursive Function 
const reqsAsyncWait = async (requests = [], data = []) => {
if (requests instanceof Array && requests.length > 0) {
const config = {
method: requests[0].method
};

return await fetch(
requests[0].url,
config
)
.then(async response => {
const json = response.json();
if (response.ok) {
const jsonData = await json;
return await reqsAsyncWait(requests.slice(1), [ ...data, ...[jsonData] ]);
}
// not this object may be empty if no err msg
throw await json;
});
}
return data;
};

// Init
try {
console.log(await reqsAsyncWait([
{
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'get'
},
{
url: 'https://jsonplaceholder.typicode.com/todos/3',
method: 'get'
},
{
url: 'https://jsonplaceholder.typicode.com/todos/7',
method: 'get'
}
], []));
} catch (error) {
console.log(error);
}

Đi đâu từ đây

Một trong những điều chính truyền cảm hứng cho bài đăng này là tôi không thể hứa hẹn với một số bài kiểm tra sau của người đưa thư của mình, vì vậy tôi phải tạo chức năng gọi lại HTTP đệ quy thực hiện nhiều yêu cầu.Postman tests, so I had to create a recursive http callback function that performed multiple requests.

Nếu bạn có quyền kiểm soát API, thì tôi sẽ giới thiệu trong hầu hết các trường hợp dữ liệu API cung cấp mọi thứ bạn cần, nhưng trong một số trường hợp, bạn có thể làm điều đó và bạn sẽ cần thực hiện các yêu cầu cho nhiều API cho tất cả dữ liệu cần thiết của bạn.

Nếu bạn có giá trị từ điều này và/hoặc nếu bạn nghĩ rằng điều này có thể được cải thiện, xin vui lòng cho tôi biết trong các ý kiến.

Vui lòng chia sẻ nó trên Twitter 🐦 hoặc các nền tảng truyền thông xã hội khác. Cảm ơn một lần nữa vì đã đọc. 🙏

Theo dõi tôi trên Twitter: @codingwithmanny và Instagram tại @CodingWithManny.twitter: @codingwithmanny and instagram at @codingwithmanny.