JavaScript如何在Promise onSuccess之外的Promise中获取分配的变量的值 [英] JavaScript How to get value of variable assigned inside Promise onSuccess outside promise

查看:408
本文介绍了JavaScript如何在Promise onSuccess之外的Promise中获取分配的变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Firefox扩展名. 我有正在读取文件内容的函数:

I'm whiting firefox extension. I got function that's reading contents of file:

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");
    },
...};

I除了line相同外,因为它是在函数外部声明的.从内部警报中,我得到了适当的值,但是从外部警报中,我得到了duckynullduck.如何解决

I except that line will be the same because is declared outside function. From inner alert I got proper value but from outer one I get duckynullduck. how to fix it

推荐答案

如何修复

不要使用外部警报.

异步代码的工作方式,您只能访问稍后执行的回调中的数据.但是,使用诺言链,不需要将所有内容都放在同一个回调或嵌套的回调中.

That's how asynchronous code works, you can only access the data in the callbacks that are executed later. However, with promise chaining, it doesn't need to go all in the same callback or in nested callbacks.

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!

这篇关于JavaScript如何在Promise onSuccess之外的Promise中获取分配的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆