在我的代码中读写文件是不阻塞的。为什么?

路由器

我正在开发用于Twitch Song Requests的机器人。机器人将读取Twitch聊天记录,搜索!sr命令并获取歌曲名称。然后,它将在Spotify中搜索歌曲,获取歌曲的URI,并将其添加到流媒体的播放列表中。

编辑:很抱歉,如果有任何“愚蠢”的代码问题(如回调@ippi通知),我真的是编程和Node JS的新手。

我现在有两个功能:一个是搜索歌曲并将接收到的URI写到文本文件中,另一个是从文件中获取URI。这是代码:

主代码(调用两个函数):

testSong(commandName, accessToken);

let uri = getUri();

console.log(uri);

搜索歌曲:

function testSong(song, accessToken) {
    let song1;
    let song2;

    song1 = song.replace("!sr", "");
    song2 = song1.trim();

    var uri = "";

    axios.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(song2) + '&type=track&market=CH&limit=1', {
        headers: {
            Authorization: 'Bearer ' + accessToken
        }
    })
        // handle success
        .then(function (response) {
            uri = response.data.tracks.items[0].uri;
            console.log("yeet")
            fs.writeFileSync('conf/uri.txt');
            logger.log('info', 'Successfully obtained URI for track ' + song2);
        })
        // handle error
        .catch(function (error) {
            logger.log('error', 'Error while accessing Spotify.');
            return error;
        });
}

获取URI:

function getUri() {
    try {
        return fs.readFileSync('conf/uri.txt', 'utf-8');
    } catch (e) {
        logger.log('error', 'Error while reading the URI text file: ' + e.stack);
    }
}

我在阅读时遇到问题。首次运行漫游器时,uri.txt文件为空。

当我在Twitch聊天中发送第一个!sr时,这首歌没有添加到Spotify播放列表中,因为在getUri函数读取文件,似乎testSong命令正在将其写入文本文件。

即使在那之后,我也必须发送一个新的!sr来添加第一首歌曲,因此每个请求都会转移。

知道为什么会这样吗?

我已经读过异步函数,但是据我了解,这不是我想要的,因为我希望在写入文本文件时阻止程序的执行,因此getUri函数可以读取当前请求的歌曲URI,并且不会转移。


编辑2:正如Felix所说,我将代码修改如下:

testSong(commandName, accessToken).then(() => console.log(getUri()));
function testSong(song, accessToken) {
    let song1;
    let song2;

    song1 = song.replace("!sr", "");
    song2 = song1.trim();

    var uri = "";

    return axios.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(song2) + '&type=track&market=CH&limit=1', {
        headers: {
            Authorization: 'Bearer ' + accessToken
        }
    })
        // handle success
        .then(function (response) {
            uri = response.data.tracks.items[0].uri;
            console.log("yeet")
            fs.writeFileSync('conf/uri.txt', uri, function (err) {
                if (err) {
                    return console.log(err);
                } else {
                    response = true;
                }
            });
            logger.log('info', 'Successfully obtained URI for track ' + song2);
        })
        // handle error
        .catch(function (error) {
            logger.log('error', 'Error while accessing Spotify.');
            return error;
        });
}

那是对的吗?

费利克斯·克林

正如我在评论中已经提到的那样,您遇到了这个问题,因为您使用的是Promise,即在尝试阅读,文件将在将来的某个时间写入

正如我们所讨论的,根本不需要使用文件来“转移”值。您可以只返回testSong(包装在promise中)的值:

function testSong(song, accessToken) {
    song = song.replace("!sr", "").trim();
    return axios.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(song2) + '&type=track&market=CH&limit=1', {
        headers: {
            Authorization: 'Bearer ' + accessToken
        }
    })
    // handle success
    .then(function (response) {
        return response.data.tracks.items[0].uri;
    });
    // errors should probably be handled by the caller
}

接着:

testSong(commandName, accessToken)
  .then(function(uri) {
    console.log(uri);
  })
  .catch(function(error) {
    // handle error
  });

一个async功能使得与承诺有点容易的工作。所以你也可以实现testSong

async function testSong(song, accessToken) {
    song = song.replace("!sr", "").trim();
    const response = await axios.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(song2) + '&type=track&market=CH&limit=1', {
    //               ^^^^^
        headers: {
            Authorization: 'Bearer ' + accessToken
        }
    });
    return response.data.tracks.items[0].uri.
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么.gitignore不忽略我的文件?

为什么我的FileOutputstream不写入文件?

为什么在Eclipse时Codility不执行我的代码?

为什么我的jar文件不包含任何类文件?

为什么我的.gitignore文件不忽略特定文件?

为什么PyQt中的这段代码允许我不选中所有单选按钮?

为什么我的代码复制文件的CSS?

为什么Visual Studio 2019不编译我的代码?

Nasm x86_64:为什么我不能读写相同的文件?

为什么我的代码不后退并将输入保留在缓冲区中?

我想知道为什么Clojure中不评估代码的优点是数据

为什么我的包装工代码不执行?

为什么我的CSS继续在.less文件中搜索代码?

为什么TextBox不绑定到我的XAML代码中的Label?

flatMap期货列表中的期货正在执行阻塞操作,那么为什么不将代码包含在阻塞{..}中呢?

为什么我的代码未写入文件?

为什么GetLastError()会阻塞我的方法?

Python为什么不运行我的bash代码?

为什么在我的代码中需要 ',' 或 ')'?

使用 thunk:为什么我的代码不按顺序打印?

为什么我的代码中的 if 语句被忽略?

为什么我在 Jupyter 上的代码不产生输出

为什么我的堆栈代码中的 pop 方法不执行?

我不知道为什么我在 jsp 文件中收到这个简单代码的错误

为什么时钟块不阻塞?

为什么这个缓冲通道没有在我的代码中阻塞?

为什么数组的相应部分在我的代码中不匹配?

为什么我的代码不这样对待并行向量?

为什么我的 .Dockerignore 文件不忽略文件?