英文:
JavaScript: Explain why the the await operator in a function declaration is the same in a function invocation?
问题
The await
in the try catch
is necessary because it ensures that the updateItem
operation is awaited and its completion is properly handled. This is important in asynchronous code to handle errors that might occur during the execution of the updateItem
operation. If you remove the await
, the code might not wait for the operation to complete before moving on to the next line, potentially causing issues with error handling and data consistency.
英文:
Consider the following I have a call to DynamoDB using this function declaration:
async putItem(param: DynamoDB.DocumentClient.PutItemInput): Promise<void> {
await this.dynamoDb.getDynamoDBDocClient().put(param).promise();
}
In a service I am using it like this:
try {
await this.dsDynamoDBService.updateItem({
TableName: this.dsConfig.aws.dynamoDB.table,
Key: {
id: docGenReq.id,
type: EItemType.REQUEST
},
UpdateExpression: 'set requestStatus = :requestStatus, requestErrored = :requestErrored',
ExpressionAttributeValues: {
':requestStatus': EDSRequestRequestDetails.COMPLETE,
':requestErrored': false
}
});
} catch (error) {
this.logService.error(error);
}
Is the await
in the try catch
even necessary? If so why?
答案1
得分: 1
是的,如果您希望try
/catch
来处理拒绝。如果没有await
,您的代码将不会对this.dsDynamoDBService.updateItem
返回的Promise执行任何操作,这意味着两件事:
-
您的代码会在Promise解决之前继续执行,并且
-
如果Promise被拒绝,您的
try
/catch
将无法捕获它
相反,使用await
,您的代码将等待Promise解决,如果解决是拒绝,它会将该拒绝传递给catch
块。
还要注意,如果没有await
,根据所示的代码,没有任何东西将处理Promise的拒绝(如果发生拒绝),这将导致未处理的拒绝,就像未处理的错误一样。如果此代码在Node.js或Deno中运行,可能会终止进程。
英文:
> Is the await
in the try
catch
even necessary? If so why?
Yes, if you want that try
/catch
to handle rejections. If you didn't have the await
, your code wouldn't be doing anything with the promise that this.dsDynamoDBService.updateItem
returns, which means two things:
-
Your code carries on before the promise is settled, and
-
Your
try
/catch
won't catch it if the promise is rejected
In contrast, with the await
, your code waits for the promise to settle, and if that settlement is a rejection, it passes that rejection to the catch
block.
Also note that if you didn't have the await
, based on the code shown, nothing would be handling the promise rejection (if one occurred), leading to an unhandled rejection, which is just like an unhandled error. If this code were running in Node.js or Deno, for instance, that might terminate the process.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论