JavaScript AJAX请求数组问题求助:不确定是回调还是AJAX故障
Hey there! Let's work through this together since you're still getting comfortable with callbacks and hitting snags with an array of AJAX requests. First, let's break down common pitfalls in your current code and array-based async handling.
1. Fix Callback & Error Handling Gaps in Your powerAmplifierInfo Function
Looking at your code snippet, there are a few immediate red flags that could be causing issues:
- Typos in response handling: You have
else if (result && res...— thatresis probably a typo forresult, right? A mistake like this will throw an error and prevent your success logic from running. - Missing callback calls in edge cases: When
TESTINGis true, you don't invoke thecbcallback even if there's an error! This means any code callingpowerAmplifierInfowill hang indefinitely, waiting for a callback that never comes. Always make sure your callback runs every time, regardless of success/error or testing mode. - Uncovered edge cases: What happens if neither
errnorresultis defined? Your current code doesn't handle that scenario, which could leave the callback untriggered too.
Here's a quick fix to address these gaps:
function powerAmplifierInfo(id, cb) { ApiGet('/system/radio-frequency/tx/' + id + '/power-amplifier', function (err, result) { // Always call the callback first if there's an error (even in testing) if (err) { if (!TESTING) { alertError("Connection error: " + err.statusText); } return cb(err); // Pass error to the caller } // Handle successful result if (result) { // Add your logic to process the result here return cb(null, result); // Pass null (no error) + result to caller } // Catch-all for unexpected cases const unknownErr = new Error("No error or result returned from request"); if (!TESTING) { alertError(unknownErr.message); } cb(unknownErr); }); }
2. Handling Arrays of AJAX Requests (The Common Async Pitfall)
Since you mentioned issues with an array of requests, the most likely problem is asynchronous order and callback management when looping through IDs. For example, if you're using a basic loop to call powerAmplifierInfo for each ID, the responses will come back in random order (since AJAX is async), and collecting results correctly can be messy with raw callbacks.
A Better Approach: Promisify Your Function
To avoid callback hell and simplify array handling, wrap your AJAX function in a Promise. This lets you use Promise.all to run all requests in parallel and get results in the same order as your input array:
// Convert powerAmplifierInfo to return a Promise function powerAmplifierInfo(id) { return new Promise((resolve, reject) => { ApiGet('/system/radio-frequency/tx/' + id + '/power-amplifier', function (err, result) { if (err) { const errorMsg = "Connection error: " + err.statusText; if (!TESTING) alertError(errorMsg); return reject(new Error(errorMsg)); } if (result) { return resolve(result); } reject(new Error("No result or error returned")); }); }); } // Use Promise.all to handle an array of IDs const amplifierIds = [1, 2, 3]; // Replace with your actual array Promise.all(amplifierIds.map(id => powerAmplifierInfo(id))) .then(allAmplifierData => { // allAmplifierData matches the order of amplifierIds! console.log("All power amplifier info:", allAmplifierData); // Pass this array to wherever you need it }) .catch(overallErr => { console.error("One or more requests failed:", overallErr); });
3. Verify Your AJAX Utility (ApiGet)
Don't rule out issues with the ApiGet function itself! Double-check:
- Does
ApiGetcorrectly handle HTTP error status codes (4xx/5xx)? Some AJAX libraries only consider network failures as errors, not bad HTTP responses. - Log the raw
errandresultvalues in your callback to confirm they match what you expect. For example, mayberesultis an empty object, or the data structure is different than you're anticipating.
内容的提问来源于stack exchange,提问作者X. Mercure

