[英]JavaScript How to get value of variable assigned inside Promise onSuccess outside promise
我在用Firefox擴展。 我有讀取文件內容的功能:
var HelloWorld = {...
getData: function () {
var env = Components.classes["@mozilla.org/processenvironment;1"].getService(Components.interfaces.nsIEnvironment);
var path = env.get("TEMP");
path = path + "\\lastcall.txt"
alert(path);
Components.utils.import("resource://gre/modules/osfile.jsm");
let decoder = new TextDecoder();
let promise = OS.File.read(path);
var line = null;
promise = promise.then(
function onSuccess(array) {
line = decoder.decode(array)
alert(line);
return line;
}
);
alert("ducky:"+line+"duck");
},
...};
我除了那一line
是一樣的,因為它是在函數外部聲明的。 從內在的戒備中我得到了適當的價值,但是從外在的戒備中我得到了duckynullduck
。 如何解決
如何解決
不要使用外部警報。
這就是異步代碼的工作方式 ,您只能訪問稍后執行的回調中的數據。 但是,使用promise鏈接,不需要將所有內容都放在同一個回調或嵌套的回調中。
let decoder = new TextDecoder();
let promise = OS.File.read(path);
return promise.then(function onSuccess(array) {
var line = decoder.decode(array);
alert(line);
return line;
}).then(function onSuccess2(line) {
alert("ducky:"+line+"duck");
return line;
}); // return the promise for the line!
getData: function () {
var env = Components.classes["@mozilla.org/processenvironment;1"].getService(Components.interfaces.nsIEnvironment);
var path = env.get("TEMP");
path = path + "\\lastcall.txt"
alert(path);
Components.utils.import("resource://gre/modules/osfile.jsm");
return OS.File.read(path).then(function(array) {
let decoder = new TextDecoder();
return decoder.decode(array);
});
},
...};
而不是返回line
而是返回line
promise,然后調用者可以執行以下操作:
var line = getData();
// When you finally need the actual line, unwrap it:
line.then(function(actualLine) {
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.