JavaScript Promise问题求助:文件上传代码逻辑异常排查
Hey there, let's break down why your Promise isn't triggering the .then() or .catch() handlers, and fix it step by step.
1. The Core Problem: Your Promise Never Resolves or Rejects
In your m1() function, you create a Promise but never call resolve() or reject() anywhere in its callback. A Promise stays in the "pending" state forever unless you explicitly tell it to transition to "fulfilled" (via resolve()) or "rejected" (via reject()). That's why your .then() and .catch() blocks never run.
2. Bonus Issue: Handling Asynchronous loadFile Calls
Assuming loadFile is an asynchronous operation (which makes sense for file uploads), your current loop just fires off all loadFile calls immediately without waiting for them to finish. Even if you added a resolve() at the end of the loop, it would run before any uploads complete. We need to wait for all uploads to finish before resolving the main Promise.
Fixed Code Example
First, let's adjust loadFile to return a Promise (if it doesn't already—you'll need to tweak its internal logic to use resolve/reject):
// Update loadFile to return a Promise function loadFile(file, category) { return new Promise((resolve, reject) => { // Your existing file upload logic goes here // Example: When upload succeeds: // resolve(`Uploaded ${file.name} successfully`); // Example: When upload fails: // reject(new Error(`Failed to upload ${file.name}`)); }); } function m1() { return new Promise(function(resolve, reject) { var files = $('#aws-upload-files')[0].files; // Handle empty file case immediately if (files.length === 0) { resolve(); return; } // Collect all upload promises into an array const uploadPromises = []; for (var i = 0; i < files.length; i++) { const selectedCategory = $('#filecategory' + i + ' option:selected').text(); uploadPromises.push(loadFile(files[i], selectedCategory)); } // Wait for ALL uploads to complete Promise.all(uploadPromises) .then(uploadResults => { // All uploads succeeded—resolve the main Promise resolve(uploadResults); }) .catch(uploadError => { // Any single upload failed—reject the main Promise reject(uploadError); }); }); } function submitFileUpload() { $('#aws-upload-submit').click(function() { m1().then(function(result) { console.log('~~~ success here ', result); window.location = 'https://example.com/'; }) .catch(function(error) { console.log('Error...', error); }); }); }
Key Fixes Explained:
- Added
resolve()for the empty file case to avoid hanging. - Used
Promise.all()to wait for everyloadFilePromise to complete before resolving the main Promise inm1(). - Explicitly called
resolve()when all uploads succeed, andreject()if any upload fails—this unblocks your.then()/.catch()handlers. - Updated
loadFileto return a Promise (critical forPromise.all()to work; if you can't modifyloadFile, wrap it in a Promise wrapper function that uses its callback logic).
内容的提问来源于stack exchange,提问作者VPY

