1

在文件读取退出后,以下将 s 保留为空:

String s;
new File('etc.stk').readAsString().then((String contents) {
    s = contents;
});
// s is null here.

有没有办法保存(或克隆)s,或者我是否被迫只在 .then 范围内使用它?

我有几千行编译器/解释器代码来解析和运行文件内容,并且不希望它们都在新的文件范围内。

编辑

为了提供更多上下文,我想做的是

new File('etc1.stk').readAsString()
    .then((String script) {     
      syntaxTree1 = buildTree(script);
    });
new File('etc2.stk').readAsString()
    .then((String script) {
      syntaxTree2 = buildTree(script);
    }); 

并且可以在后续代码中访问 syntaxTree1 和 syntaxTree2。如果可以的话,我会围绕飞镖之路。

4

1 回答 1

3

EDIT
(this code is tested)

import 'dart:async' as async;
import 'dart:io' as io;

void main(args) {
// approach1: inline
  async.Future.wait([
     new io.File('file1.txt').readAsString(),
     new io.File('file2.txt').readAsString()
  ]).then((values) {
    values.forEach(print);
  });

// approach2: load files in another function
  getFiles().then((values) {
    values.forEach(print);
  });
}

async.Future<List> getFiles() {
  return async.Future.wait([
     new io.File('file1.txt').readAsString(),
     new io.File('file2.txt').readAsString()
  ]);
}

output:

file1
file2

file1
file2

EDIT END

hint: the code is not tested

// s is null here

is because this line is executed before

s = contents

This code

new File('etc.stk').readAsString()

returns a future that is enlisted in the event queue and is executed when the actual 'thread' of execution is finished.

If you had provided more code I would have a better context for a proposed solution.
What you could do is

String s;
new File('etc.stk').readAsString().then((String contents) {
    s = contents;
}).then((_) {
// s is **NOT** null here.
});

or

//String s;
new File('etc.stk').readAsString().then((String contents) {
    //s = contents;
    someCallback(s)
});
// s is null here.

void someCallback(String s) {
  // s is **NOT** null here
}

or

Future<String> myReadAsString() {
  return new File('etc.stk').readAsString();
}

myReadAsString().then((s) {
  // s is **NOT** null here
}

see also:

and maybe

于 2014-05-14T17:21:08.033 回答