You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Photoshop CEP HTML面板evalScript返回变量undefined问题求助

解决Photoshop CEP面板中psDocumentsLength返回undefined的问题

这个问题的核心是**csInterface.evalScript是异步操作**,你现在的代码逻辑犯了一个常见的异步编程错误——在异步操作完成前就去访问它的结果。

问题分析

你调用check_PSDocumentsLength()后立刻执行alert(psDocumentsLength),但此时csInterface.evalScript还没完成和Photoshop的通信,回调函数里的psDocumentsLength = result根本还没执行,所以变量还是初始的undefined。

修复方案

我们需要把依赖异步结果的逻辑放到回调函数里,或者用Promise封装让代码更易读。

方案1:直接在回调中处理结果(最小改动)

把alert(以及后续需要用到文档数量的逻辑)移到evalScript的回调里,或者给check_PSDocumentsLength传入一个回调函数:

(function() { 
    'use strict'; 
    var csInterface = new CSInterface(); 
    var psDocumentsLength; 

    function init() { 
        themeManager.init(); 
        $(document).ready(function() { 
            // 传入回调函数处理结果
            check_PSDocumentsLength(function(docCount) {
                psDocumentsLength = docCount;
                alert(psDocumentsLength); // 现在能拿到正确的文档数量了
                // 这里可以继续写需要用到文档数量的面板逻辑
            }); 
        }); 
    }; 

    init(); 

    function check_PSDocumentsLength(callback) {
        var chosenFunction = 'checkDocumentsLength()'; 
        csInterface.evalScript(chosenFunction, function(result) {
            // 注意:evalScript返回的是字符串,要转成数字类型
            var docCount = parseInt(result, 10);
            callback(docCount);
        }); 
    }; 
}());

方案2:用Promise封装(更优雅的异步处理)

如果你的面板逻辑比较复杂,用Promise+async/await可以让异步代码看起来像同步代码:

(function() { 
    'use strict'; 
    var csInterface = new CSInterface(); 

    function init() { 
        themeManager.init(); 
        $(document).ready(async function() { 
            try {
                var psDocumentsLength = await check_PSDocumentsLength();
                alert(psDocumentsLength);
                // 后续依赖文档数量的逻辑写在这里
            } catch (err) {
                console.error('获取文档数量失败:', err);
            }
        }); 
    }; 

    init(); 

    function check_PSDocumentsLength() {
        return new Promise((resolve, reject) => {
            var chosenFunction = 'checkDocumentsLength()'; 
            csInterface.evalScript(chosenFunction, function(result) {
                if (result === 'undefined' || result === null) {
                    reject(new Error('无法获取Photoshop文档数量'));
                } else {
                    resolve(parseInt(result, 10));
                }
            }); 
        });
    }; 
}());

额外注意点

别忘了确保Photoshop端的checkDocumentsLength函数是正确定义的(通常放在JSX文件中):

// 这部分代码要在Photoshop的JSX环境中运行
function checkDocumentsLength() {
    // 返回当前打开的文档数量
    return app.documents.length;
}

内容的提问来源于stack exchange,提问作者Simos Sigma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:22:40