简体   繁体   English

等待输入结束再执行下一个代码?

[英]Wait input end before executing next code?

I'm using this piece of code to to try triggering an input and then read the file path, so I can load it as text in a div : 我正在使用这段代码来尝试触发输入,然后读取文件路径,因此可以将它作为文本加载到div

var fileinput = $("input[id=fileDialog]").trigger('click');

var fs = require('fs');

fs.readFile(path, 'utf8', function(err, txt) {
  if (err) {
    return;
  }

  document.getElementById('content').innerText=txt
});

Problem is, it seems that the jQuery part is async, so the following code doesn't wait for it to finish, and that generate problems. 问题是,jQuery部分似乎是异步的,因此以下代码不会等待其完成,从而产生了问题。

How can I make the code wait for the input to close before executing? 如何使代码在执行之前等待输入关闭?

I think the problem is that your fs.readFile Asynchronously reads the entire contents of a file while execution moves to next statement. 我认为问题在于您的fs.readFile在执行移至下一条语句时异步读取文件的全部内容。

you can use Synchronous version of fs.readFile() . 您可以使用fs.readFile()同步版本。 ie fs.readFileSync that returns the contents of the path. fs.readFileSync返回路径的内容。

Full details are here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options 完整细节在这里https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM