[英]Return value received in anonymous method inside function
我有一個使用Google API的Javascript函數。 我希望此函數在出現錯誤時返回狀態,或者在請求確定時返回place對象。
我的嘗試不正確,因為我在匿名方法中指定了返回值。 我不確定如何傳遞此返回值。 這是我的嘗試:
function GetDetail(id)
{
var service = new google.maps.places.PlacesService($('#results').get(0));
service.getDetails({
placeId: id
}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
return place;
}
else {
return status;
}
});
}
var myReturnObj = GetDetail(1234);
如果我在函數頂部聲明了返回值,由於匿名函數不會立即返回,因此我仍然無法返回它,因此GetDetail()方法會在設置之前返回。 與var return = service.getDetails()
我不確定寫這個的正確方法。 我嘗試了各種不同的方法,但現在卻使自己感到困惑。
如何獲取GetDetail()以返回位置/狀態對象?
謝謝你的幫助
您需要使用回調或Promise,因為您無法從異步調用中返回(這是JS中的異步特性)-使用回調的方法如下:
function GetDetail(id, callback) {
var service = new google.maps.places.PlacesService($('#results').get(0));
service.getDetails({placeId: id}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
callback(place);
} else {
callback(status);
}
});
}
GetDetail(1234, function(resp) {
var myReturnObj = resp; //do your work in here!
});
這就是為什么Promise很棒的原因。 ES6,ES7和新版本的Node.js將會嚴重依賴它們。
你可以說:
GetDetail(1234).then(function(info){
var myInf0 = info;
//then do what you want with it...
res.render('page', {info: myInfo})
}
要么:
GetDetail(1234)
.then(function(info){
return db.insert({_id: info.id, stuff: info.arrayOfStuff})
.then(function(){
return db.findOne({_id: info.id})
.then(function(){
res.render('page', {id: info.id})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.