编写文件async node.js,了解为什么不起作用

时间:2019-02-08 20:28:23

标签: node.js

我具有此功能并且工作正常:

        const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')
        let playlistString = JSON.stringify(this.playlist)

        mkdirp(config.PLAYLIST_PATH, function (_) {
            fs.writeFile(playlistPath, playlistString, function (err) {
                if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
                console.log('The album has been added to the playlist');
            })
        })

但是如果我要删除var playlistString并直接使用JSON.stringify则无法正常工作,则该文件将使用未定义的格式写入。

        const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')

        mkdirp(config.PLAYLIST_PATH, function (_) {
            fs.writeFile(playlistPath, JSON.stringify(this.playlist), function (err) {
                if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
                console.log('The album has been added to the playlist');
            })
        })

为什么?

1 个答案:

答案 0 :(得分:2)

该问题是由this作用域引起的。在编写this.playlist的第二个代码块中,它引用调用函数。在这种情况下,您的回调function (err)...拥有this

要解决此问题,请将this分配给一个变量,然后使用该变量引用您想要的上下文

const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json');

// Hold the value of "this" in a variable "ref"
const ref = this;

mkdirp(config.PLAYLIST_PATH, function (_) {
    fs.writeFile(playlistPath, JSON.stringify(ref.playlist), function (err) {
        if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
        console.log('The album has been added to the playlist');
    })
})