TypeScript中如何调用取数函数并跨文件传递查询结果?
获取getAllTips返回的Tips数组方法
你已经在main.ts里导出了getAllTips函数,只需要在目标文件中导入该函数,并处理它返回的Promise即可(因为async函数默认返回Promise),具体步骤如下:
1. 导入函数
在需要获取tips数组的文件(比如anotherFile.ts)中,导入getAllTips:
import { getAllTips } from './main'; // 注意:路径要根据你的文件实际位置调整,比如如果main.ts在utils目录下,路径就是'./utils/main'
2. 两种方式获取tips数组
方式一:使用async/await(推荐,代码更简洁)
因为await只能在async函数内部使用,所以需要包裹在一个异步函数中:
async function handleTips() { try { const tips = await getAllTips(); // 这里就可以直接使用tips数组了 console.log(tips); // 执行你的业务逻辑,比如渲染tips、存储到状态中等 } catch (error) { console.error('获取tips失败:', error); } } // 调用这个异步函数 handleTips();
方式二:使用Promise的.then()链式调用
如果不想用async函数,也可以用传统的Promise链式调用:
getAllTips() .then(tips => { // 处理tips数组 console.log(tips); }) .catch(error => { console.error('获取tips失败:', error); });
优化建议:完善原函数的错误处理
你的getAllTips函数目前只有try/finally,没有捕获异常,建议添加catch块处理查询过程中的错误,这样调用者能捕获到异常并处理:
// 修改main.ts中的getAllTips函数 async function getAllTips() { const tips: any = []; try { const snapshot = await ref .child("tips") .orderByChild("cont") .startAt(1) .endAt(5) .get(); if (snapshot.val()) { for (let key in snapshot.val()) { let value = snapshot.val()[key]; tips.push(value.get("tips")); } } } catch (error) { console.error('查询tips数据出错:', error); throw error; // 抛出错误,让调用者的catch捕获 } finally { return tips; } }
内容的提问来源于stack exchange,提问作者Mehmet Ata
相关产品推荐
相关产品推荐

