CNode

想问,怎么把callback函数的内容拿出来。。

问答
Nnichousha233发布于5 年前最后回复5 年前14 回复3749 浏览0 收藏
const fs = require('fs')
var text
fs.readFile('./test.txt', {encoding:''}, function(err, data){
    if(err){
        console.log(err);
    }else{
        text = data.toString()
        console.log(data.toString());
    }   
});
console.log('This is the end.')
console.log('out:',text)

输出

This is the end.
out: undefined
This is a test file. 

怎么让那个out等到text被赋值了再输出啊

查看回复

回复 (14)

Y
yviscool#1·5 年前

nodejs 回调是异步的, 最原始的方法不能用同步的逻辑写, 你要嘛在 else 里面处理, 要嘛用现在的标准 Promise, async/await

Q
qichangjun#3·5 年前
	const fs = require('fs')
	var text
	
	function getText(){
	  return new Promise((resolve,reject)=>{
		fs.readFile('./test.txt', {encoding:''}, function(err, data){
		  if(err){
			  reject(err)
		  }else{
			  text = data.toString()
			  resolve(text)
		  }   
	  });
	  })
	} 
	
	(async (){
	  let text = await getText()
	  console.log('This is the end.')
	  console.log('out:',text)
	})()
G
guojingkang#4·5 年前

尽量不要用 Sync 同步函数。。对于nodeJs原生的 callback api ,统一可以用util.promisify转成 promise

I
ilss#5·5 年前

await fs.readFile(.....)

I
InCodingNowLiu#6·5 年前

推荐 fs-extra, 简单实用 https://www.npmjs.com/package/fs-extra

L
leizongmin#7·5 年前

现在 fs 标准库已经支持 Promise 了 https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_promise_example:

const fs = require('fs/promises');

(async function(path) {
  try {
    await fs.unlink(path);
    console.log(`successfully deleted ${path}`);
  } catch (error) {
    console.error('there was an error:', error.message);
  }
})('/tmp/hello');
N
nichousha233#8·5 年前
引用 qichangjunconst fs = require('fs') var text function getText(){ return new Promise((resolve,reject)= { fs....

@qichangjun 非常感谢,你的脚本的第17行 我测试了下 符合我的需求,不过提醒下,你的脚本的第17行缺了个“=>”好像

N
nichousha233#9·5 年前

@index-js 是的,对于这个例子是没错的,但是我其实想要对于其他的没有类似readFileSync的函数的解决办法

N
nichousha233#11·5 年前
引用 ilssawait fs.readFile(.....)

@ilss 谢谢您的回复

N
nichousha233#13·5 年前
引用 leizongmin现在 fs 标准库已经支持 Promise 了 https://nodejs.org/dist/latest v14.x/docs/api/fs.html fs promise example...

@leizongmin 谢谢您的回复,我想要的是一种通解,而不是针对这个特定的文件读取函数的特解。

W
wucpeng#14·5 年前

let ss = fs.createReadStream('./test.txt'); let str = ""; for await (let chunk of ss) { str += chunk; } console.log('str', str);

参与回复
登录后即可参与回复。登录