【问题标题】:Why is this Lambda function async?为什么这个 Lambda 函数是异步的?
【发布时间】:2021-02-03 07:55:01
【问题描述】:

此 Lambda 函数执行 http 请求,然后将数据写入 DynamoDB。我想知道为什么该函数是异步设置的。如果它不是异步的,那不是一样吗?据我所知, await 告诉代码在 httprequest() 完成后暂停并继续。不是和同步运行代码一样吗?

exports.handler = async (event) => {
    try {
        const data = await httprequest();

        for (var i = 0; i < data.d.results.length; i++){
            var iden = Date.now();
            var identifier = iden.toString();
            datestring.substring(4,6) + "-" + datestring.substring(6,8);
            
        //add to dynamodb
        var params = {
            Item: {
                id: identifier,
                date: data.d.results[i].DAY_T,
            },
        TableName: 'DB'
        };
        await docClient.put(params).promise();
        }
        
        console.log('Document inserted.');
        return JSON.stringify(data);
    } catch(err) {
        console.log(err);
        return err;
    }
};

【问题讨论】:

  • 另外,await docClient。 --- 要使用 await 它所在的功能需要是异步的。
  • 不准确,不。 await 让 JavaScript 引擎有机会运行其他一些 JS,而不是像 Promise 那样阻塞等待被调用函数的响应。
  • 这和同步运行代码不一样不,还是异步的。

标签: javascript node.js asynchronous aws-lambda


【解决方案1】:

async/await 是语法糖,它使 编写代码 看起来与编写同步代码的方式相似,同时保留了异步代码的所有优点。

基本上是这样的:

var result = await doSomethingAsync();
console.log(result);

其实是这样的:

doSomethingAsync().then(result => {
    console.log(result);
});

如果你想象做很多这样的事情,它很快就会变得非常嵌套。当您也包含错误处理时,then/catch 方法会变得冗长而冗长。 async/await 让您以更自然的方式使用 try/catch - 与您习惯用于同步代码的方式相同。

你的代码在一个循环中执行多个await,我需要建立一个承诺列表并在那里执行Promise.all。这一切都很难写得不出错。

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2023-01-23
    • 1970-01-01
    • 2015-07-21
    • 2021-08-07
    • 2021-01-10
    相关资源
    最近更新 更多