2014-08-30 80 views
-1

我不知道问题出在哪里。它不断返回一个空数组。也就是说,movieIds总是空的。无法从javascript函数获取返回值

function getMoviesInCinema(theCinema){ 
    var cinema = theCinema; 
    var query = new Parse.Query("showing"); 
    var movieIds = []; 

    query.equalTo("cinema", { 
     __type: "Pointer", 
     className: "Cinema", 
     objectId: cinema 
    }); 
    query.find().then(function(results) { 
     if(results.length > 0){ 
      for (var i = 0; i < results.length; i++) { 
       movieIds.push(results[i].get("movie")); 
      } 

     } 
     else{ 
      console.log("Could be an error"); 
     } 
    }); 
    return movieIds; 

} 

回答

-3

而不是使用

movieIds.push(results[i].get("movie")); 

尝试使用

movieIds.add(results[i].get("movie")); 

它可能会解决您的问题。

+0

它没有工作 – user3679294 2014-08-30 09:14:11

+0

ü可以尝试打印“结果[我] .get(“movie”)“... – Prashant2329 2014-08-30 09:17:05

+1

这更不正确,OP的原始代码与实际问题无关。 '.push'是在数组末尾添加某些东西的正确方法('[] .add'不存在)。 – 2014-08-30 09:18:11

2

这是因为当您从函数返回时查询还没有完成。你应该让你的函数需要一个回调来代替:

function getMoviesInCinema(theCinema, callback){ 
    var cinema = theCinema; 
    var query = new Parse.Query("showing"); 

    query.equalTo("cinema", { 
     __type: "Pointer", 
     className: "Cinema", 
     objectId: cinema 
    }); 
    query.find().then(function(results) { 
     if(results.length > 0){ 
      callback(results); 
     } 
     else{ 
      console.log("Could be an error"); 
     } 
    }); 
} 

然后调用它是这样:

getMoviesInCinema(theCinema, function(movieIds) { 

    console.log(movieIds); 

}); 
+0

我需要查询的结果作为可比较的。 var VariableName = resultofquery – user3679294 2014-08-30 09:21:17

+0

@ user3679294:你不能,至少不能让你立即有用地使用数组。同样,正如詹姆斯所说,你的函数在**信息可用之前返回**。 – 2014-08-30 09:22:01

0

的这里的问题是,query.find()运行异步。这意味着您的getMoviesInCinema函数返回之前query.find调用您的then回调。

由于query.find是异步的,您的函数不能直接返回ID。 (它可以返回数组,但数组将会是空的。)相反,它也应该提供Promise或允许回调。

不知道,什么承诺lib中你使用所以这里使用回调选项:

function getMoviesInCinema(theCinema, callback){ 
// Receive the callback --------------^ 
    var cinema = theCinema; 
    var query = new Parse.Query("showing"); 
    var movieIds = []; 

    query.equalTo("cinema", { 
     __type: "Pointer", 
     className: "Cinema", 
     objectId: cinema 
    }); 
    query.find().then(function(results) { 
     if(results.length > 0){ 
      for (var i = 0; i < results.length; i++) { 
       movieIds.push(results[i].get("movie")); 
      } 

     } 
     else{ 
      console.log("Could be an error"); 
     } 
     if (callback) {    // <===== 
      callback(movieIds);  // <===== Call it 
     }       // <===== 
    }); 
} 

用法:

getMoviesInCinema(42, function(movieIds) { 
    // Use movieIds here 
});