Sunday 30 October 2016

javascript - Await function when used as a function parameter does not get resolved before the function is run



The following code work as expected using async/await:



try {
let feedbacks = await feedbackService.get(this.feedBackOdataModel);
this.feedBackJsonModel.setProperty('/Avaliacoes', feedbacks.results);



} catch (error) {
dialogService.showErrorDialog("Erro na obtenção das pesquisas de satisfação", error.statusText + '-' + error.statusCode);
throw new Error(error);
}


The execution is halted until feedbackService gets resolved.



But this:




... 
this.feedBackJsonModel.setProperty('/Avaliacoes', await
feedbackService.get(this.feedBackOdataModel).results);
...


I imagine the result should be the same but it seens the the promise gets resolved after the setProperty is run.


Answer



Your two code examples are not equivalent. In the first, you are awaiting




feedbackService.get(this.feedBackOdataModel)


which is presumably a promise, and in the second, you are awaiting



feedbackService.get(this.feedBackOdataModel).results


which is presumably undefined. So indeed, the await has essentially no effect, and undefined is passed into setProperty almost immediately.




To fix - use parentheses to correctly indicate what you are awaiting:



this.feedBackJsonModel.setProperty(
'/Avaliacoes',
(await feedbackService.get(this.feedBackOdataModel)).results
);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...