首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何等待对不是promise但包含promise的函数的调用结果?

如何等待对不是promise但包含promise的函数的调用结果?
EN

Stack Overflow用户
提问于 2019-06-04 05:06:59
回答 3查看 115关注 0票数 -1

首先,我知道这里已经有很多关于异步的东西了,但我断断续续地看了很多地方,都没有找到任何似乎可以回答这个问题的东西,至少对于这个新手来说是这样的。

背景

我有一个函数foo,它依赖于另一个包含promise的函数googlePlaces的结果,但整个函数不是promise。

JS

代码语言:javascript
复制
var googleMapsClient = require('@google/maps').createClient({
  key: <API_KEY>
  Promise: Promise
});
...
function foo() {
  
  var point = [49.215369,2.627365]
  var results = googlePlaces(point)
    console.log('line 69')
    console.log(results)
    
    // do some more stuff with 'results'
 
   }

function googlePlaces(point) {

    var placesOfInterest = [];

    var latLng = (point[0]+','+point[1])
    var request = {
      location: latLng,
      radius: 10000
    };

  
    googleMapsClient.placesNearby(request).asPromise()
    
    .then(function(response){        
       placesOfInterest.push(response.json.results)      
       }) 

    .finally(function(){
       console.log('end of googlePlaces function:')
       console.log(placesOfInterest);
       return(placesOfInterest);
       })
    
}

控制台日志:

第69行

未定义

googlePlaces函数结束

我可爱的阵列

我尝试过的

我曾尝试将foo设置为异步函数,并将results更改为= await googlePlaces(point),但仍未定义,而且还抛出了UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

我可以将第69行之后的foo中的所有内容都移到googlePlaces函数中,这是可行的,但是为了代码的整洁和可读性,如果它能留在foo中就更好了

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56434543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档