Как ожидать результата вызова функции, которая НЕ является обещанием, но содержит обещание? - PullRequest
0 голосов
/ 04 июня 2019

Во-первых, я знаю, что здесь уже есть много информации об асинхронности, но я смотрел во многих местах, включая и выключая SO, и не нашел ничего, что, по-видимому, отвечает на этот конкретный вопрос, по крайней мере, для неподготовленных глаз этогонуб.

Фон

У меня есть функция foo, которая зависит от результата другой функции googlePlaces, которая содержит обещание, но общая функция не является обещанием.

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
undefined
конец функции 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)

Я могу переместить все из foo после строки 69 в функцию googlePlaces, и это работает, но для аккуратности и читабельности кода было бы намного лучше, если бы он мог остаться в foo

Ответы [ 3 ]

3 голосов
/ 04 июня 2019

В googlePlaces() до:

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

, затем в foo() до:

async function foo(){
  ...    
  var results = await googlePlaces(point);
  results.then( /* do you then stuff here */);
}
0 голосов
/ 04 июня 2019

Без необходимости слишком много менять свой код, вы можете обернуть обещание Google Места в другое обещание, которое всплывает до foo ().Оттуда вы можете обработать результаты.

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);
           })
    });
}
0 голосов
/ 04 июня 2019

Если вы уверены, что foo возвращает обещание, обещайте, чтобы оно связывалось с:

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..
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...