2014-06-11 37 views
1

我是whiting firefox扩展。 我得到的功能是阅读文件的内容:JavaScript如何获取Promise onSuccess中承诺的变量值Promise

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。如何解决它

+0

'OS.File.read'做一些事情异步。只有在promise被解析并且你传递给'then'的函数被执行之前'line'才会有值。将依赖'line'的代码移到回调中。 –

回答

5

如何解决它

不要使用外警戒。

这就是how asynchronous code works,您只能访问稍后执行的回调中的数据。但是,在承诺链接的情况下,它不需要全部使用同一个回调函数或嵌套的回调函数。

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! 
1
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你行返回的承诺,那么调用者可以这样做:

var line = getData(); 

// When you finally need the actual line, unwrap it: 

line.then(function(actualLine) { 

});