所以我有这个名为Events的类,我试图从我的服务器调用异步函数。我试图了解我出错的地方/如何解决另一个异步调用中的承诺。任何提示或提示将不胜感激。
这是我打电话的事件功能:
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 :(得分: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)
}
答案 1 :(得分:0)
您没有正确宣布承诺,df['CAGR'] = (first_column.div(second_column).pow(1./2)- 1)).sub(1))*100
然后你可以这样使用
return new Promise( function(resolve, reject){}
另外参考,请查看承诺docs。