本文介绍了Node.js promisifaction 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
创建一个名为 big.file 的文件并存储值:
Created a file name big.file and stored values:
const fs = require('fs');
const file = fs.createWriteStream('./big.file');
for(let i=0; i<= 2; i++) {
file.write('1\n2\n3');
}
file.end()
尝试过promisifaction,但我不确定是不是这样.
Tried promisifaction, but I am not sure is this way or not.
function readFile('./big.file','utf8'){
return new Promise(function(resolve,reject){
fs.readFile('./big.file', 'utf8',function(err,data){
if(err) reject (err);
else{
console.log(data);
const lines =data.split('\n');
console.log(lines);
const numbers = lines.map(Number);
const oddNumbers = numbers.filter(n => n%2 === 1);
console.log('Odd numbers count:', oddNumbers.length);
}
});
});
};
推荐答案
当没有错误时,您需要使用数据调用 resolve
回调.
You need to call resolve
callback with the data, when there is no error.
function readFile(filename, encoding) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, encoding, function(err, data) {
if (err) {
return reject (err);
}
console.log(data);
const lines =data.split('\n');
console.log(lines);
const numbers = lines.map(Number);
const oddNumbers = numbers.filter(n => n%2 === 1);
console.log('Odd numbers count:', oddNumbers.length);
resolve(oddNumbers);
});
});
};
这篇关于Node.js promisifaction 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!