gpt4 book ai didi

javascript - 尝试理解 Promise()

转载 作者:行者123 更新时间:2023-12-03 03:52:00 26 4
gpt4 key购买 nike

所以我 fork 了一个 Javascript 项目,并尝试对其进行一些扩展,同时从中学习。我的 Javascript 技能确实很新鲜,但我认为这会很有趣。然而,我真的很挣扎于所有的 promise ,以至于我有很多 promise 和可实现的目标,我真的不明白它是如何定位的。我无法得到最终结果,也不明白为什么。

所以我从这个开始(我禁用了一个功能以保持简单):

export const calculateMovingAverage = (event, context, callback) =>
Promise.all([
// ma.calculateMovingAverage('Kraken', 'AskPrice'),
ma.calculateMovingAverage('Coinbase', 'SellPrice'),
])
.then((tx) => {
console.log('tx', tx);
}).catch((err) => {
console.error('err', err);
callback({ statusCode: 500, body: { message: 'Something went wrong' } });
});

因此调用ma.calculateMovingAverage():

calculateMovingAverage(exchange, metric) {
const self = this;
const args = {
minutes: 10,
period: 60,
currency: `${self.cryptoCurrency}`,
metricname: `${metric}`,
localCurrency: `${self.localCurrency}`,
namespace: `${exchange}`,
};
var promisedland = new Promise((resolve, reject) => {
self.cloudwatch.getMetricStatistics(args, (err, data) => {
if (err) { return reject(err); }

if (!Array.isArray(data.Datapoints) || !data.Datapoints.length) { return reject("No Datapoints received from CloudWatch!")}

data.Datapoints.forEach(function(item) {
self.ma.push(item.Timestamp, item.Average);
});

resolve(ma.movingAverage());
})
})
promisedland.then((results) => {
return new Promise((resolve, reject) => {
const body = {
value: results,
metricName: `${metric} @ 180 MovingAverage`,
namespace: `${exchange}`
};
self.cloudwatch.putAverageMetricData(body, function(err, result) {
if (err) { return reject(err); }
resolve(result);
});
}
)
}).catch(function(err) {
return reject(err);
});
}

现在,正如您在calculateMovingAverage() 中看到的那样,我尝试调用两个AWS 方法。 getMetricStatisticsputAverageMetricData

第一个,getMetricStatistics 函数工作得很好,因为我从 AWS 很好地取回了数据点。

函数本身:

  getMetricStatistics(args) {
return this.cloudwatch.getMetricStatistics({
EndTime: moment().subtract(180, 'minutes').utc().format(),
Dimensions: [
{
Name: 'CryptoCurrency',
Value: args.currency
},
{
Name: 'LocalCurrency',
Value: args.localCurrency
},
{
Name: 'Stage',
Value: process.env.STAGE || 'dev'
}
],
MetricName: args.metricname,
Period: Number(args.period),
StartTime: moment().subtract(190, 'minutes').utc().format(),
Statistics: ['Average'],
Unit: 'Count',
Namespace: args.namespace || 'Coinboss',
}).promise();
}

接下来,我想通过 MovingAverage 模块传递响应,并希望通过 putAverageMetricData 函数将 MA 的结果放入 CloudWatch Metrics 中:

putAverageMetricData(args) {
return this.cloudwatch.putMetricData({
MetricData: [
{
MetricName: args.metricName,
Timestamp: moment().utc().format(),
Unit: 'Count',
Value: Number(args.value),
},
],
Namespace: args.namespace || 'Coinboss',
}).promise()
.then(function(result) {
console.log('putAverageMetricData', result);
});
}

这就是我迷路的地方。我看起来数据永远不会到达 putAverageMetricData 函数。控制台输出仅显示 console.log('tx', tx); ,内容如下:

2017-07-15T19:37:43.670Z 118ff4f0-6995-11e7-8ae7-dd68094efbd6 tx [ undefined ]

好的,所以我没有返回calculateMovingAverage()then。它解决了未定义的错误。我仍然没有从 putAverageMetricData() 函数中获取日志记录,这让我觉得我仍然缺少一些东西。

我希望有人能指出我正确的方向

最佳答案

您的 getMetricStatisticsputAverageMetricData 方法已经返回 promise ,因此请避免 Promise constructor antipattern计算移动平均中!并且不要忘记最后从那里返回一个 promise :

calculateMovingAverage(exchange, metric) {
const args = {
minutes: 10,
period: 60,
currency: this.cryptoCurrency,
metricname: metric,
localCurrency: this.localCurrency,
namespace: exchange,
};
return this.cloudwatch.getMetricStatistics(args).then(data => {
if (!Array.isArray(data.Datapoints) || !data.Datapoints.length)
throw new "No Datapoints received from CloudWatch!";

for (const item of data.Datapoints) {
this.ma.push(item.Timestamp, item.Average);
}
return this.ma.movingAverage();
}).then(results => {
const body = {
value: results,
metricName: `${metric} @ 180 MovingAverage`,
namespace: exchange
};
return this.cloudwatch.putAverageMetricData(body);
});
}

关于javascript - 尝试理解 Promise(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122402/

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