I wrote a AWS lambda function which buys €X worth of some currency on an exchange. For this I first have to find out the current price (getAskPrice
), then calculate the amount to buy and post the order (buyLimitOrder
). I've implemented both operations as promises, buyLimitOrder
gets the result of getAskPrice
as one of the arguments. The result of buyLimitOrder
(if successful) should be returned as the result of the lambda function.
Here's the relevant code fragment:
const getAskPrice = new Promise(function(resolve, reject){
got(TICKER_URL).then(response => {
let result = JSON.parse(response.body);
let ask = Number(result.ask);
if (!isNaN(ask)) {
resolve(ask);
} else {
throw new Error("Could not parse the ask price from [" + BTCEUR_TICKER_URL + "] response:\n" + response.body);
}
}).catch(reject);
});
const buyLimitOrder = function(customerId, key, secret, value, askPrice) {
let amount = value / askPrice;
let roundedAmount = Math.ceil(amount * Math.pow(10,5)) / Math.pow(10,5);
let order = createAuthData(customerId, key, secret);
order.amount = roundedAmount;
order.price = askPrice;
return new Promise(function(resolve, reject) {
console.log("Buying " + roundedAmount + " of BTC for price " + askPrice + " for total value of " + (roundedAmount * askPrice) + ".");
got.post(BUY_LIMIT_ORDER_URL, {
body : order,
form: true
}).then(response => {
let result = JSON.parse(response.body);
resolve(result);
}).catch(reject);
});
};
const getAskPriceAndBuyLimitOrder = function(customerId, key, secret, value) {
return new Promise(function(resolve, reject) {
getAskPrice
.then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
.catch(reject);
});
};
exports.handler = (event, context, callback) => {
doWithBitstampProperties()
.then(bitstampProperties =>
getAskPriceAndBuyLimitOrder(bitstampProperties.customerId, bitstampProperties.key, bitstampProperties.secret, VALUE)
.then(result => callback(null, result))
.catch(error => callback(error)))
.catch(error => callback(error));
};
Full code can be found here.
This works, but I was not sure this is how promises should be chained. For instance, calling .then(resolve).catch(reject)
on buyLimitOrder(...)
does not feel right:
return new Promise(function(resolve, reject) {
getAskPrice
.then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
.catch(reject);
});
Generally, the code does not feel elegant.
return GetAskPrice.then(askPrice => ...)
worked the same way as your above code. Have you tried this? \$\endgroup\$