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

如何从Wix Velo的JavaScript查询函数返回数组?

问题分析

你的代码核心问题在于异步操作的执行时机:wixData.query(...).find()是异步方法,它的回调(.then()里的代码)会在当前同步代码执行完之后才触发。而你的initialize函数在调用异步查询后立刻返回了ActiveComedians数组,这时候异步查询还没完成,数组里还没有数据,自然无法访问到预期结果。

解决方案

要正确获取异步查询的结果,你需要让函数等待异步操作完成后再返回数据。推荐使用async/await语法,让异步代码逻辑更清晰:

const allComedians = "Comedians";
let shows = ["Heat 1","Heat 2","Heat 3","Heat 4","Heat 5","Showcase 1","Showcase 2","Showcase 3"];
let showKeys = ["1","2","3","4","5","6","7","8"];

async function initialize () {
    // 先找到匹配的演出对应的key
    const matchIndex = shows.findIndex(show => show === project.title);
    if (matchIndex === -1) {
        // 无匹配演出时返回空数组
        return [];
    }
    const targetShowKey = showKeys[matchIndex];
    
    try {
        // 等待异步查询完成
        const results = await wixData.query(allComedians)
            .contains("showKey", targetShowKey)
            .eq("isActive", true)
            .find();
        
        // 直接提取需要的标题并返回数组
        return results.items.map(item => item.title.trim());
    } catch (err) {
        console.log(err);
        // 出错时返回空数组或按需处理错误
        return [];
    }
}
调用方式

因为initialize现在是异步函数,调用时需要用.then()或者await来获取结果:

// 方式1:使用then回调
initialize().then(activeComedians => {
    console.log(activeComedians); // 此处可拿到正确的结果数组
});

// 方式2:在async函数内使用await
async function getComedians() {
    const activeComedians = await initialize();
    console.log(activeComedians);
}
getComedians();
关键注意点
  • 所有返回Promise的异步操作(比如wixData.query().find()),必须用.then()或await等待结果,不能直接同步获取。
  • async函数会自动返回Promise,函数内部的return值会作为Promise的resolve结果。
  • 尽量避免在异步回调里修改外部变量再返回,这种写法极易因异步时机问题导致数据错误。

内容的提问来源于stack exchange,提问作者Nicholas Gutzman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:12:10