【问题标题】:Return value from custom async function [duplicate]从自定义异步函数返回值[重复]
【发布时间】:2017-08-24 03:14:12
【问题描述】:

我需要从 google geocode api 返回 lat-lng 坐标,然后用它做点什么。所以,我的代码是这样的:

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']);
}

但是f['location'] 总是有 undefined

【问题讨论】:

  • 您忘记从getLocationForName 转至return</strong> getJSON(...).then(...);。它将返回一个承诺,即f['location'] 将被分配承诺。如果这不是您想要的,请先等待承诺解决:getLocationForName(...).then(location => f['location'] = location)。如果您不能 100% 确定异步函数的工作原理,不妨看看 How do I return the response from an asynchronous call?
  • 是的,这个例子真的很有帮助,谢谢!所以,getLocationForName(...).then(location => f['location'] = location) 它看起来非常优雅,但我收到了这个错误:Uncaught TypeError: Cannot read property 'then' of undefined
  • 返回 await 也会返回 promise,而不是结果。您必须将结果分配给变量然后返回该变量的值。
  • 今晚我的速度很慢=(你能打印一个例子吗?
  • "但是我得到了这个错误:..."你仍然需要在getLocationForName中做return getJSON(...).then(...);

标签: javascript google-maps asynchronous async-await


【解决方案1】:

你需要使用回调函数:

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;
    });
}

【讨论】:

  • 是的,如果在 js 中使用f['location'],这种方法可以正常工作,但我需要将所有f 数组放入 php。所以,在$_POST['insertDailyQuest'] 中这个数组是不存在的。 imagegetLocationForName(city+f['street']+'+'+f['house'], function(location){ f['location'] = location; }); $.post('php/proxy.php',{insertDailyQuest: f}, function(response){ console.log(f); console.log(response); });
  • 所有依赖位置的处理都应该进入回调函数内部:getLocationForName(city+f['street']+'+'+f['house'], function(location){ f['location'] = location; $.post('php/proxy.php',{insertDailyQuest: f}, function(response){ console.log(f); console.log(response); }); });
猜你喜欢
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多