Promise封装Papa.parse后无法向.then传递结果的技术问题
Hey Ian, I see exactly what's going on here—your data processing logic works fine, but you're not letting the Promise know when it's done and what result to pass to .then(). Let's break this down and fix it:
The Root Problem
When you create a Promise, you have to explicitly call its resolve function (in your code, that's the complete parameter you defined) to signal that the async operation is finished and pass along the final result. Right now, you're processing the data into tArray but never sending that array back through the Promise. That's why your .then() callback never runs and you see no console output.
Modified Working Code
Here's the adjusted version with the key fix highlighted:
Papa.parsePromise = function(file) { return new Promise(function(complete, error) { Papa.parse(file, { delimiter: "", newline: "", download: true, error, complete: function(results){ var tArray=[]; var data = results.data; var temp = data.length; var filledRowCounter=0; filePresentMarker=1; // Note: Consider making this a local variable if possible to avoid global scope pollution for(var i=0;i<temp;i++){ var row = data[i]; if (row[0]!==""){ filledRowCounter++; tArray.push(row); } } // 👇 This is the missing line! Resolve the Promise with your processed array complete(tArray); } }); }); }; Papa.parsePromise("Data/tables.csv") .then(function(processedResults) { console.log(processedResults); // Now this will log your filtered tArray! }) .catch(function(parseError) { // Don't forget to handle errors too! console.error("Parse error:", parseError); });
Key Changes Explained
- Added
complete(tArray);at the end of the PapaParsecompletecallback: This tells the Promise to transition from "pending" to "fulfilled" and passes your filteredtArrayas the resolved value, which will be received by the.then()callback. - Added a
.catch()handler to catch any parsing errors (since you're passing theerrorfunction to PapaParse, errors will reject the Promise, and this lets you handle them gracefully). - Added a note about
filePresentMarker—if this doesn't need to be a global variable, it's better to declare it withvar,let, orconstto keep it within the scope of the callback.
Now when you run this, your .then() will log the filtered array exactly as you expect!
内容的提问来源于stack exchange,提问作者IanR

