[英]File APIs Javascript FileReader onload
我正在使用帶Javascript的文件API。
我需要等待onload方法的完成,該怎么辦?
reader.onload = function (e) {
contents = reader.result;
var addAttchCallBack = loadRequestExecutor();
addAttchCallBack.done(function (data) {
alert("ok");
})
};
alert("Ko");
我總是看到“ Ko”之前
注意:函數loadRequestExecutor()正確返回一個Promise obj。
謝謝,NK
您確實需要研究異步行為和回調,然后繼續理解promises
,因為您的示例是回調和promise的奇怪結合,但是,請嘗試從根本上解釋發生了什么:
您總是首先看到KO
,因為第一個示例執行此操作:
因此,基本上, onload
函數只會在文件加載后(異步)被調用,因此下一行的alert
將立即執行。
在注釋中,您的第二個示例是:
$.when(reader.onload = function (e) {
contents = reader.result;
return loadRequestExecutor();
}).done(function (a) {
alert("ok");
});
alert("KO");
轉換為:
when
但是不執行!!! 最終結果不會使承諾返回等待,這可能就是您的意思,因此它將永遠無法按預期工作。
建議:
我不太了解這些插件,但是如果您要等待,那么您似乎需要記錄一個與加載請求執行程序有關的Promise。
// Create the loadRequestExecutor and record the promise
var addAttchCallBack = loadRequestExecutor();
// Setup the onload callback
reader.onload = function (e) {
contents = reader.result;
alert("ok - file load is done");
};
// Listen for the loadRequestExecutor to complete
addAttchCallBack.done(function (data) {
alert("Ko - loadRequestExecutor is done");
})
alert("I am just an alert that will happen first, as everything above is asynchronous!");
您的總體目標不清楚,因此該答案主要側重於說明您的兩次嘗試為何不如您預期的那樣進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.