Lor*_*ABA 1 javascript scope firefox-addon promise
我正在whiting 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");
},
...};
Run Code Online (Sandbox Code Playgroud)
我除了那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!
Run Code Online (Sandbox Code Playgroud)