gpt4 book ai didi

javascript - 尝试从 ES6 类函数解析 promise 链

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:46 25 4
gpt4 key购买 nike

所以我有一个名为 Events 的类,并且我正在尝试从我的服务器调用异步函数。我试图了解我哪里出错了/如何解决另一个异步调用中的 promise 。任何提示或技巧将不胜感激。

这是我调用的事件函数:

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

最佳答案

你的整个结构太复杂了。删除注释时,您可以将代码简化为:

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

关于javascript - 尝试从 ES6 类函数解析 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com