问题描述
我试图从FOR循环中强制对Apex进行多次调用。但奇怪的是,只有前6个交易成功。休息都失败了。在开发人员文档中没有提及从LWC到Apex的标注数量的任何此类限制。
之所以采用这种方法,是因为每个标注都将遵循一组新的Apex限制。
import { LightningElement,api,wire,track } from 'lwc';
import insertRecords from '@salesforce/apex/FileUploaderXCtrl.insertRecords';
export default class FileUploadExample extends LightningElement {
file;
filename;
filecontent;
output = [];
buttonVisible = false;
position = 0;
get acceptedFormats() {
return ['.csv'];
}
uploadFiles(event) {
console.log('hey! No of Callouts: ----------->' + this.output.length);
for (let index = 0; index < this.output.length; index++) {
console.log('Making Callouts Now! Watch Out --------');
insertRecords({ jsonObjinput: this.output[index] })
.then(() => { console.log('*******\n\nHurray! Its Working....\n\n********'); })
.catch((error) => { console.log('Go Home...'); });
}
}
handleUploadFinished(event) {
if (event.target.files.length > 0) {
this.filename = event.target.files[0].name;
this.file = event.target.files[0];
var reader = new FileReader();
var jsonObj = [];
reader.readAsText(this.file,"UTF-8");
reader.onload = (evt) => {
console.log('File Name: ----------->' + this.filename);
this.filecontent = evt.target.result;
let rows = this.filecontent.split('\n');
let header = rows[0].split(',');
rows.shift();
console.log('Header: ----------->' + header);
rows.forEach(element => {
let data = element.split(',');
let obj = {};
for (let index = 0; index < header.length; index++) {
obj[header[index].trim()] = data[index].trim();
}
jsonObj.push(obj);
});
let result = new Array(Math.ceil(jsonObj.length / 10000)).fill().map(_ => jsonObj.splice(0,10000));
result.forEach(element => {
this.output.push(JSON.stringify(element));
});
console.log('Apex Input Parameter: ----------->' + this.output);
console.log('No of Callouts: ----------->' + this.output.length);
}
reader.onloadend = (evt) => {
this.buttonVisible = true;
}
reader.onerror = (evt) => {
if (evt.target.error.name == "NotReadableError") {
console.log('An Error Occured Reading this File!!');
alert('An Error Occured Reading this File!!');
}
}
}
}
}
解决方法
在stackexchange上已经有一些很好的记录。这被称为boxcarring,由于浏览器能够限制并行调用的次数,因此lwc进行boxcarring。
https://salesforce.stackexchange.com/questions/293025/boxcaring-is-removed-from-lwc-components
您应该查看它们,以了解为什么salesforce会在lwc中进行盒装。
简而言之,您可以选择与诺言进行异步以避免这些,否则其他解决方法将是setTimeout。
这两种方法都无法提供良好的用户体验,相反,您应该探索实现此目的的其他替代方法,包括以下
- 使用Bulk API v2.0进行所有数据操作
- 在类似Heroku的对象上构建UI界面,并使用python或Node进行处理,而不是使用apex进行资源密集型工作。