我无法获取 flatListData,因为它似乎只是本地的 我可以在 query.find().then(function(results) 内获取 flatList 数据 除此之外我什么也没有!
我尝试使用 Async/Await 进行此操作,但不起作用
const W = Parse.Object.extend("W");
const query = new Parse.Query(W);
var flatListData = [];
query.find().then(function(results) {
for (var i=0; i < results.length; i++){
flatListData.push(String(results[i].get("AlphabetCode")));
}
alert(flatListData) //{"a" , "b" , "s" , "w"}
});
alert(flatListData) // Nothing!
module.exports = flatListData;
最佳答案
这里的问题是您正在尝试创建异步导出语句,这是严格禁止的。
首先,是的,flatListData
是全局的,而不是本地范围的。您面临的实际问题是,虽然您的查询结果已有效地传递给变量,但作为异步函数需要一些时间才能完成。当您在第二个 alert()
和 module.exports
中调用变量时,您的异步查询尚未完成,因此尚未分配新值,并且您最终只会向外部脚本发送 undefined
值。
现在,处理它的唯一可能的方法是强制您的 module.exports 等待变量被分配,这意味着要么将其范围限定在您的 Promise 中(以及您的第一个 >alert()
),或使用 await
语句。但是:
The await operator is used to wait for a Promise. It can only be used inside an async function.
所以就这样了。您唯一的退出路径是限制您的 module.exports
...这是完全禁止的。您永远不想将您的导出称为顶级范围(即全局范围)。
重新定义问题
您的目标是导出对象中的内容集,以便在许多地方使用。
但请记住,您无法异步导出任何内容。在您的情况下,您唯一的选择是导出一个函数,并在需要时调用它。
现在是解决方案
getFlatListData.js,或者任何你叫它的东西
// Those are globally scoped. They will only be calculated on
// initialization, and not during outside import calls
const W = Parse.Object.extend("W");
const query = new Parse.Query(W);
// We wrap everything inside an async function, which will be exported
function getFlatListData() {
// We return a promise, to allow outer calls to the result
return new Promise(resolve => {
// Also, avoid var. If you need a variable which isn’t constant, prefer let.
let flatListData = [];
// Prefer arrow functions here
query.find().then(results => {
// Works like your classic for(…) loop, but more efficient
for(const result of results) {
flatListData.push(String(result.get("AlphabetCode")));
}
// Resolve your function and send the result back
resolve(flatListData);
});
});
}
module.exports = getFlatListData;
现在,在您的外部脚本中:
main.js,或其他
// Assuming you are using commonJS syntax
const getFlatListData = require(‘path_to_your_script/getFlatListData’);
[. . .]
getFlatListData().then(result => {
// Now you can use your FlatListData aliased as result
});
// OR
const myAsyncFunction = async() => {
const myVariable = await getFlatListData();
// Use myVariable as you please now
};
这里可以进行很多改进,例如使用 map()
函数来分配 flatListData
,或者添加 reject
您 promise 处理任何错误。但你已经明白了主要想法。
永远不要进行异步导出,如果必须这样做,则意味着您需要重新考虑您的代码!
关于javascript - 我无法从 query.find().then(function(results) 获取数据,它似乎只是本地的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969866/