Unable to get callback from function

时间:2017-08-14 07:06:27

标签: node.js

Trying to get the variable random_song from the function functions.random_song

Function:

functions.random_song = () => {
  fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
    if (err) {
      console.log(`${`ERR`.red} || ${`Error fetching song from auto playlist ${err}`.red}`);
    }
    let songs = data.split('\n');
    songs.splice(-1, 1);
    var random = Math.floor(Math.random()*songs.length);
    let random_song = (songs[random]);
    return random_song;
  })
}

Attempting to callback the random song

functions.random_song(song => { 
console.log(song)
})

The code just return undefined Ideas?

4 个答案:

答案 0 :(得分:1)

你的职能:

functions.random_song = (callback) => {
  fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
    if (err) {
      // Do stuff
      return callback(err);
    }
    // Do stuff
    callback(null, random_song);
  })
}

然后叫它:

functions.random_song((err, song) => { 
   // Do stuff
});

您可能想要阅读有关使用Promise / async-await而不是回调的更多信息。

答案 1 :(得分:0)

functions.random_song = () => {
  let data = fs.readFileSync('auto_playlist.txt', 'utf8');
  let songs = data.split('\n');
  songs.splice(-1, 1);
  var random = Math.floor(Math.random()*songs.length);
  let rand_song = (songs[random]);
  return rand_song;
}

console.log(functions.random_song())

让它工作,谢谢你的帮助< 3

答案 2 :(得分:0)

以下是使用Promise异步处理文件读取和数据处理任务的代码

const fs = require('fs')
const functions = {}
functions.random_song = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
            if (err) {
                console.log(err)
                reject(err)
            }
            let songs = data.split('\n');
            songs.splice(-1, 1);
            var random = Math.floor(Math.random()*songs.length);
            let random_song = (songs[random]);
            resolve(random_song);
        })
    })
}

functions.random_song()
.then(song => console.log('Song Name', song))
.catch(err => console.error('Error fetching songs', err))

console.log('It will be executed before promise is resolved')

答案 3 :(得分:-1)

fs.readFile是异步的,您的函数将在读取文件之前返回。使用fs.readFileSync instead。像这样:

functions.random_song = () => {
  const data = fs.readFileSync('auto_playlist.txt', 'utf8');
    let songs = data.split('\n');
    songs.splice(-1, 1);
    var random = Math.floor(Math.random()*songs.length);
    let random_song = (songs[random]);
    return random_song;
}