简体   繁体   English

我的 Javascript 函数不断返回未定义

[英]My Javascript function keeps returning undefined

I have a function,called getIt() , which finds the top 5 venues through the Foursquare API.我有一个名为getIt()的函数,它通过 Foursquare API 查找前 5 个场地。 Inside the getVenues() , i push the name of the first item of the venues in places array, and as it seems it exists normally inside of it.getVenues() ,我将场地的第一个项目的名称推getVenues()数组中,看起来它通常存在于其中。 However when I call the function and set it to the variable place, I get undefined .但是,当我调用该函数并将其设置为变量位置时,我得到undefined What's wrong?怎么了?

 var place=getIt(); console.log(place[0]); function getIt(){ var params={ "near":"Athens,Gr", "query":"sushi", "limit":5 } var places=[]; foursquare.getVenues(params, function(error, venues) { console.log(venues.response.venues[0].name); places.push(venues.response.venues[0]) console.log(places[0].name); }); //console.log(venues.response.venues[0]); return places; }

Your code is asynchronous.您的代码是异步的。 It means that the function you use does not block the execution of the code following after it.这意味着您使用的函数不会阻止其后代码的执行。 You essentially send a request, but do not wait for it, you just say "when response arrives, populate this array with the results, if error did not occur, otherwise handle the error (which you should)".您本质上发送了一个请求,但不要等待它,您只需说“当响应到达时,用结果填充这个数组,如果没有发生错误,否则处理错误(您应该这样做)”。 In your getIt function you create an array and actually return it rightaway.在您的getIt函数中,您创建一个数组并实际立即返回它。 It will be populated later.稍后会填充。 But immediately after the execution of the getIt function the places array is empty, thus its first element is undefined .但是在getIt函数执行后, places数组立即为空,因此它的第一个元素是undefined You have two options:您有两个选择:

Do your manipulations inside the callback, or provide callback to the getIt function:在回调中进行操作,或向getIt函数提供回调:

function getIt(params, callback) {
   foursquare.getVenues(params, function(error, venues) {
   if (!error) callback(venues)
});
}
 getIt(someParams, function(venues) {// handle venues here})

The other option is the async keyword.另一个选项是async关键字。 If you use a version of Javascript that supports it (ES6 or higher, if I remember correctly), and the foursquare API has methods returning a Promise you can give it a try如果您使用支持它的 Javascript 版本(ES6 或更高版本,如果我没记错的话),并且 Foursquare API 具有返回 Promise 的方法,您可以尝试一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM