我无法从 query.find().then(function(results) 获取数据,它似乎只是本地的

I can't get data from query.find().then(function(results) it seems to be just local

我无法获取 flatListData,因为它似乎只是本地的 我可以在 query.find().then(function(results) 在那之外我得到了 None!

我也用 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 等待变量被赋值,这意味着要么在你的承诺中限定它的范围(连同你的第一个 alert() ),或使用 await 语句。但是:

MDN Documentation

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 来处理任何错误。但你已经掌握了主要思想。

切勿进行异步导出,如果您必须这样做,则意味着您需要重新考虑您的代码!