等待不等待执行?

时间:2019-11-12 06:28:39

标签: node.js aws-lambda

以下代码:

async function addData() {
    console.log("Adding a new record");
    var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

    var params = {
        TableName: 'mytable-xxx',
        Item: {
            'name': { S: 'xxx },
            'vendor': { S: 'yy'}
        }
    };

    // Call DynamoDB to add the item to the table
    await ddb.putItem(params, function (err, data) {
        if (err) {
            console.log("addData Error", err);
        } else {
            console.log("addData Success", data);
        }
    });
    console.log("Finishing adding a new record");
}

结果是我得到了输出:

Adding a new record
Finishing adding a new record

为什么等待没有成功? 这是我的AWS Lambda执行。

谢谢

1 个答案:

答案 0 :(得分:1)

请勿混用回调和承诺。您可以使用ddb.put()。promise()代替回调。见下文:

let result = await ddb.put(params).promise();
console.log(result) 

您的代码将如下所示:

async function addData() {
    console.log("Adding a new record");
    var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

    var params = {
        TableName: 'mytable-xxx',
        Item: {
            'name': { S: 'xxx' },
            'vendor': { S: 'yy' }
        }
    };



    // Call DynamoDB to add the item to the table

    try {
        let result = await ddb.put(params).promise();
        console.log("addData Success", result);
    } catch (err) {
        console.log("addData Error", err);
    }

    console.log("Finishing adding a new record");
}