javascript - Return value from custom async function -
this question has answer here:
- how return response asynchronous call? 21 answers
i need return lat-lng coordinates google geocode api, , it. so, code seems this:
async function getjson(url){ try { const response = await fetch(url); return await response.json(); } catch (err) { console.error(err.message); } } function getlocationforname(address){ getjson(geocodeurl+address+apikey).then(function(location){ return location.results[0].geometry.location; }); } somefunc(){ f['location'] = getlocationforname(city+f['street']+'+'+f['house']); }
but f['location']
alwais have undefined value
you need use callback function:
function getlocationforname(address, callback){ getjson(geocodeurl+address+apikey).then(function(location){ if (callback) callback(location.results[0].geometry.location); }); } somefunc(){ getlocationforname(city+f['street']+'+'+f['house'], function(location){ f['location'] = location; }); }
wiki
Comments
Post a Comment