ElectronJS:在使用 invoke/handle 时不需要日志记录方法会多次触发

问题描述

正如标题所说。我的 ElectronJS 项目有这个问题。当我尝试记录调用处理程序的输出时,记录会发生多次,即使该函数仅运行一次。这可能是什么原因?

对于创建的每个类对象,该函数仅运行一次。请参阅底部的 GIF 以查看“正在执行”的问题。

我已尝试删除处理程序和侦听器,但这只会使下一个对象无法调用 downloadPoster..

在此先感谢您的帮助。

以下是对象的实例化和“处理”方式。

// On drop
window.ondrop = async function(e) {
    e.preventDefault();
    body.classList.remove('file-hover');
    for (var [i,file] of Object.entries(e.dataTransfer.files)) {
        var x = new Movie(file.path);
        await x.process();
    }
    return false;
};

这是 renderer.js

类中的函数
/**
* Download poster file for movie
*/
async downloadPoster() {

    // This is the url used to search for the poster we want
    var searchUrl = new URL(Config.api.searchUrl);
    searchUrl.search = new URLSearchParams({
        page: 1,api_key: Config.api.key,query: this.#movie.tags.title,year: this.#movie.tags.year
    });

    // Search for poster in the main thread
    await axios.get(searchUrl.href)
    .then(async (resp) => {

        // No results
        if (resp.data.total_results <= 0) {
            this.log('No poster found','error');
            return;
        } 
            
        // Invoke poster download
        const result = await ipcRenderer.invoke('downloadPoster',{
            src: Config.api.posterUrl + resp.data.results[0].poster_path,dest: path.join(this.#movie.new.absolutePath,Config.api.posterFilename)
        })
        
        // This shows "undefined"    
        this.log(result);

    })
    .catch(async (err) => {
            this.log('Could not search for poster: ' + err,'error');
    });

} 

这是来自 main.js 的处理函数

// Download poster
ipcMain.handle('downloadPoster',async (event,args) => {

    await axios.get(args.src,{ responseType: 'stream' })
    .then(async (resp) => {

        const writeStream = fs.createWriteStream(args.dest);

        // Write data to file
        await resp.data.pipe(writeStream);
        
        // When finished,send reply back
        writeStream.on('finish',async () => {
            return {
                success: true,message: 'Poster downloaded'
            }
        });

        // On error writing,send reply back
        writeStream.on('error',async (err) => {
            return {
                success: false,message: 'Could not write poster to file: ' + err
            }
        });

    })
    .catch(async (err) => {
        return {
            success: false,message: 'Could not download poster: ' + err
        }
    });

});

No actual pirated material. Just test folders.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)