2016-07-17 2 views
0

Итак, у меня есть этот класс под названием Events, и я пытаюсь вызвать функцию async с моего сервера. Я пытаюсь понять, где я ошибся/как разрешить обещание внутри другого асинхронного вызова. Любые подсказки или советы были бы весьма признательны.Попытка решить цепочку обещаний из функций класса ES6

Это функция событие Я звоню:

Event.prototype.getCost = function(name_of_place){ 
return new Promise(function(){ 
     var placeID; 
     var GooglePlaces = require("node-googleplaces"); 
     const places = new GooglePlaces(API_KEY); 
     const params = { 
      location: '40.689247,-123.102192', 
      radius: 1000 
     }; 
     var query = 
     { 
      query: name_of_place 
     }; 
     // ASYNC call 
     places.textSearch(query).then((res) => { 
      console.log("FIRST ASYNC CALL"); 
      console.log(res.body.results[0].place_id); 
      placeID = res.body.results[0].place_id; 
      var request_place_details={ 
       placeid : placeID 
      }; 
      console.log(request_place_details); 

      return request_place_details; 

     }).then((request_place_details) => { 
      console.log("SECOND ASYNC CALL"); 
      places.details(request_place_details).then((res) => { 
       console.log(res.body.result.price_level + " S"); 
       var cost = res.body.result.price_level; 
       //trying to resolve getCost promise 
       //resolve(this.cost); 
       return cost; 
      }).then((cost) => { 
       console.log("ATTEMPT TO RESOLVE ORIGINAL"); 
       this.cost = cost; 
       console.log(cost + " F"); 

       //WANT TO RETURN THIS VALUE IN THE END 
       resolve(this.cost); 
      }); 
     }); 
    })}; 

Это где я звоню его от:

//Server is currently serving on port 8420 
app.listen(8420,function startServer(){ 
console.log("Listening on :: " + 8420); 
var Event1 = new events(7,10,'New York'); 
// console.log(Event1.getCost('Sushi')); 
Event1.getCost('Sushi').then(res => { 
     console.log(res); 
}) 
}); 
+0

Это [антишаблон] (https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns), чтобы обернуть другое обещание в новом обещании и не нужно. Просто выполните 'return places.textSearch (query) .then (...)' и полностью избавитесь от внешнего обещания. – jfriend00

+1

Весь смысл обещаний - это цепочки асинхронных вещей - верните обещание, и вы можете '. Then' от вашей основной цепочки обещаний, а не вкладывать обещания! – towerofnix

ответ

4

вся ваша структура - путь к сложному. при снятии комментариев, вы можете уменьшить код к этому:

Event.prototype.getCost = function(name_of_place){ 
    var GooglePlaces = require("node-googleplaces"); 
    const places = new GooglePlaces(API_KEY); 
    //const params = { 
    // location: '40.689247,-123.102192', 
    // radius: 1000 
    //}; 

    return places.textSearch({ query: name_of_place }) 
     .then(res => res.body.results[0].place_id) 
     .then(placeID => places.details({ placeid : placeID })) 
     .then(res => res.body.result.price_level) 
} 
0

Вы не заявляющего обещание правильно, return new Promise(function(resolve, reject){}

И тогда вы можете использовать это так

places.details(request_place_details).then((res) => { 
      console.log(res.body.result.price_level + " S"); 
      var cost = res.body.result.price_level; 


      // Just resolve it here. 
      resolve(cost);     
     }); 


// And here, res == cost. 
Event1.getCost('Thai Moon').then(res=> { 
    console.log(res); 
}) 

Также для справки, ознакомьтесь с обещанием docs.