【发布时间】:2019-05-06 13:37:10
【问题描述】:
我有一个回调,它等待来自 HTTP 请求的响应,如果文件成功上传,该请求会以“完成”一词进行响应,并且我通过回调发出一个请求以每次上传单个文件。
我想要的是,当响应“完成”时,我想用do-while 循环上传多个文件,我正在考虑用 Promise 来做到这一点,但我真的不知道怎么做。
我现在的代码:
var self = this;
let i = 0;
let fileInput = fileCmp.get("v.files");
do {
// my callback
self.uploadHelper(component, event, fileInput[i]);
console.log("Uploading: " + fileInput[i].name);
i++;
} while (i < fileInput.length);
我想要的只是当我得到响应“完成”或来自呼叫的其他内容时才转到i=1(第二个文件)。
我的回调是从uploadHelper() 调用的:
uploadChunk: function (component, file, fileContents, fromPos, toPos, attachId) {
console.log('uploadChunk');
var action = component.get("c.saveTheChunk");
var chunk = fileContents.substring(fromPos, toPos);
action.setParams({
parentId: component.get("v.recordId"),
fileName: file.name,
base64Data: encodeURIComponent(chunk),
contentType: file.type,
fileId: attachId
});
action.setCallback(this, function (a) {
console.log('uploadChunk: Callback');
attachId = a.getReturnValue();
fromPos = toPos;
toPos = Math.min(fileContents.length, fromPos + this.CHUNK_SIZE);
if (fromPos < toPos) {
this.uploadChunk(component, file, fileContents, fromPos, toPos, attachId);
} else {
console.log('uploadChunk: done');
component.set("v.showLoadingSpinner", false);
// enabling the next button
component.set("v.nextDisabled", false);
component.set("v.uploadDisabled", true);
component.set("v.clearDisabled", true);
component.set("v.showToast", true);
component.set("v.toastType", 'success');
component.set("v.fileName", '');
component.set("v.toastMessage", 'Upload Successful.');
}
});
$A.getCallback(function () {
$A.enqueueAction(action);
})();
}
【问题讨论】:
-
你在哪里传递回调?
-
顺便说一句,
self是不必要的。this只能在不同的功能之间有所不同。 -
你标记为
my callback的部分实际上并不是一个回调函数。 -
@Andy 是的,它是一个数组。
-
@Adam 当然。虽然它简化了同步流控制的使用,就像 OP 希望使用的那样。
标签: javascript promise salesforce-lightning