简体   繁体   English

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

[英]How to await the result of a call to a function which is NOT a promise, but contains a promise?

Firstly I know there is already a lot of stuff about async on here, but I have looked in many places on and off SO and not found anything which seems to answer this particular question, at least not to the untrained eyes of this noob. 首先,我知道这里已经有很多关于异步的东西了,但是我在SO上和下的很多地方都没看过,却没有发现任何似乎可以回答这个特定问题的东西,至少对于这个菜鸟未经训练的眼睛而言。

Background 背景

I have a function foo which depends on the result of another function googlePlaces which contains a promise, but the overall function is not a promise. 我有一个函数foo ,它取决于另一个包含 promise的函数googlePlaces的结果,但是整个函数不是一个promise。

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

}

console log: 控制台日志:

line 69 69行
undefined 未定义
end of googlePlaces function googlePlaces函数的结尾
[my lovely array] [我可爱的阵列]

What I've tried 我尝试过的

I've tried making foo an async function, and changing results to be = await googlePlaces(point) , but I still get undefined, and also it throws 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) 我尝试使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) 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)

I can move everything from foo after line 69 to be within the googlePlaces function, and that works, but for neatness and readability of code it would be much better if it could stay in foo 我可以将第69行之后的foo所有内容移动到googlePlaces函数中,并且可以正常工作,但是对于代码的简洁性和可读性,如果可以保留在foo ,那就更好了

In googlePlaces() do: googlePlaces()执行以下操作:

return googleMapsClient.placesNearby(request).asPromise();

then in foo() do: 然后在foo()执行:

async function foo(){
  ...    
  var results = await googlePlaces(point);
  results.then( /* do you then stuff here */);
}

If you are sure that foo returns a promise, Promisfy it to chain with then: 如果您确定foo返回了一个promise,则Promisfy将其与以下链接:

function foo() {

  var point = [49.215369,2.627365]
  var results = googlePlaces(point)
   return results;
 }

(new Promise(function(res){
     res(foo());
})).then(function(result){
//do something with result..
})

Without having to change your code too much you can wrap the google places promise within another promise that bubbles up to foo(). 无需过多更改代码,您就可以将Google Places Prom包装在另一个达到foo()的Promise中。 From there you can handle the results. 从那里您可以处理结果。

function foo() {

    var point = [49.215369,2.627365]
    var promise = googlePlaces(point)

    promise.then((results) => {
        // do stuff with 'results'
        console.log(results)
    });

}

function googlePlaces(point) {

    var placesOfInterest = [];

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

    return new Promise((resolve) => {
        googleMapsClient.placesNearby(request).asPromise();
        .then(function(response){        
           placesOfInterest.push(response.json.results)      
           }) 

        .finally(function(){
           console.log('end of googlePlaces function:')
           console.log(placesOfInterest);
           // resolve the promise 
           resolve(placesOfInterest);
           })
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM