2 回答

TA貢獻1853條經驗 獲得超18個贊
您期望callback函數在調用函數時執(zhí)行synchronously。
更新類似于下面的代碼
async function getRandomLine(filename) {
return new Promise(function (resolve, reject) {
fs.readFile(filename, function (err, data) {
if (err) reject(err); // Reject in case of error
data += "";
var lines = data.split("\n");
line = lines[Math.floor(Math.random() * lines.length)];
console.log(line);
resolve(line); // Resolve if success
});
});
}
async function generateRandomCouple(f1, f2) {
male = await getRandomLine(f1);
female = await getRandomLine(f2);
return male + " & " + female;
}
(async function() {
couple = await generateRandomCouple("./maleNames.txt", "./femaleNames.txt");
console.log(couple);
})();

TA貢獻1829條經驗 獲得超9個贊
fs.readFile異步運行。getRandomLine立即返回未定義。要使其按預期工作,您可能希望使用async-await. 是這樣的:
async function getRandomLine(filename) {
var x= await fs.readFile(filename, 'binary');
....
return new Buffer(x)
}
添加回答
舉報