以下AWS lambda代码(高度简化):
'use strict';
var aws = require('aws-sdk');
var docClient = new aws.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
var inputorder = initInputAndDbParams(event);
queryOrders(inputorder)
.then(findSuitableOrder.bind(null, inputorder)) //findOrder requires query result
.then(placeNewOrder(inputorder));
callback(null, "ORDER OK");
}
function queryOrders(inputorder) {
return new Promise(function(resolve, reject) {
docClient.query(inputorder.dbparams.qparams, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data); // gets back the query result array
}
}
}
// Recursive!!
function findSuitableOrder(inputorder) {
return new Promise(function(resolve, reject) {
if (array.length === 0 || orderamount === 0) resolve();
order = array.shift();
if (order.article = inputorder.article) {
deleteOrder(inputorder)
.then(placeNewOrder);
}
}
}
function deleteOrder(inputorder) {
return new Promise(function(resolve, reject) {
docClient.delete(inputorder.dbparams.delparams, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
}
}
function placeNewOrder(inputorder) {
return new Promise(function(resolve, reject) {
docClient.put(inputorder.dbparams.wparams, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
}
}
function placeOrderDelivery(inputorder) {
return new Promise(function(resolve, reject) {
docClient.put(inputorder.dbparams.odparams, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
}
}
function initInputAndDbParams(event) {
var inputorder = {
article: "example",
price: 54
amount: 1
};
return inputorder;
}
函数调用的预期顺序是:
实际结果如:
我在所有函数中使用promises,但initInputAndDbParams除外,它返回一个值。递归调用findSuitableOrder以遍历订单数组。
如何获得所需的函数调用序列?
答案 0 :(得分:0)
我明白了:
queryOrders(inputorder).then(function (orders) {
return findSuitableOrder(inputorder, orders);
}).then(function() {
return placeNewOrder(inputorder);
}).catch(function (err) {
console.log(err);
一切都按顺序进行。
感谢您的所有帖子和帮助!