首先,我知道这里已经有很多关于异步的东西了,但我断断续续地看了很多地方,都没有找到任何似乎可以回答这个问题的东西,至少对于这个新手来说是这样的。
背景
我有一个函数foo
,它依赖于另一个包含promise的函数googlePlaces
的结果,但整个函数不是promise。
JS
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
中就更好了
https://stackoverflow.com/questions/56434543
复制相似问题