CNode

这个异步应该怎么返回?

问答
Ggithub-amazingboy发布于7 年前最后回复7 年前6 回复4941 浏览0 收藏
import fs from 'fs';
	fs.readFile('index.html',function(err,data){
		var html = data.toString('utf-8');
		var reg = /(<template[\s]*src=["|'])([\w.]+)(["|'][\s]*><\/template>)/ig;
		var results = reg.test(html);
		if(results){
			var finalStr = html.replace(reg, function(){
				var importFile = arguments[2];
				if(fs.existsSync(importFile)){
					//return fs.readFileSync(importFile).toString('utf-8');
					fs.readFile(importFile,function(err,data){
						var partHtml = data.toString('utf-8');
						return partHtml; //怎么返回呢?
					});
				}else{
					return "hello";
				}
				return 'test'
			})
			console.log(finalStr)
		}
    })
查看回复

回复 (6)

I
im-here#1·7 年前

callback吧 你想用return那就用Promise封装一下吧

W
waitingsong#2·7 年前

外层包个 Promise(resolve => {....}) 然后 resolve(partHtml)

T
TimLiu1#3·7 年前

fs.readFileSync 全部可以写成同步的啊,nodejs api操作文件都有同步api,这个代码简直太难看了

O
ounana#4·7 年前

异步不能返回

G
github-amazingboy#5·7 年前

2019-08-26 14_33_19-启动.png

这样加了 还是报错.

L
linliny#6·7 年前

const html = fs.readFileSync('index.html','utf8')

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