Async module controllers in Orchard CMS? - orchardcms

Is it possible to make async calls inside Actions in Orchard CMS module controlle?
something like
public async Task<ActionResult> Index()
{
var result = await Service.Get();
return View();
}
Right now it just continue the execution and it doesn't get back to return View()

Deadlocking perhaps?
var result = await Service.Get().ConfigureAwait(false);
See this question for more information about ConfigureAwait(false): Best practice to call ConfigureAwait for all server-side code

Related

Playwright - How to access TestInfo outside of test function?

In Playwright, is there any way to access current TestInfo outside of a test function?
I have some tests that need access to the current testInfo.snapshotDir. However, the 'e_compareImages' function that needs the testInfo is nested several layers deep. It is not practical to pass the testInfo from the test function all the way to the function that needs that info.
I know e_compareImages() already has some access to the current testInfo because the function calls toMatchSnapshot() (from Jest's expect library), and the function pulls the correct file from the current testInfo.snapshotDir
Is there any way for functions in the actionHelper file to access current testInfo outside of an expect assertion?
I've posted what I believe are the relevant portions of the files below.
// LoginPage.test.js File
const { test } = require('#playwright/test');
test("Verify logo on Login page", async () => {
await loginPage.verifyLogo();
});
// actionHelper.js File
const { expect } = require('#playwright/test');
async e_compareImages(selector, expectedImageFileName) {
let locator= await this.page.locator(selector);
const actualImage = await locator.screenshot({scale: 'device'});
await expect(actualImage).toMatchSnapshot(expectedImageFileName);
}
I've tried importing Playwright's globals.js library and using its currentTestInfo(), but I have been unable to get it to work.
Is there another library or a way to extend an existing library that would do what I need?
Please let me know if you need any additional information.
You can access TestInfo object outside of a test function using the test method's second argument:
async e_compareImages(testInfo, selector, expectedImageFileName) {
// ...
const actualImage = await locator.screenshot({scale: 'device'});
await expect(actualImage).toMatchSnapshot(testInfo, expectedImageFileName);
}
Now, when you call e_compareImage function you can pass the TestInfo object as an argument:
test("Verify logo on Login page", async (testInfo) => {
await loginPage.verifyLogo(testInfo);
});
I found what I was looking for. You can use the below code to require the globals library
var _globals = require("../node_modules/#playwright/test/lib/globals");
Then you can use this function to get the current testInfo object directly (without having to pass the object through however many intermediary functions)
// Get the current test's testInfo object
async getCurrentTestInfo() {
const curTestInfo = await (0, _globals.currentTestInfo)();
return await curTestInfo
}

How to pass data in a promise chain, I am using sequelize

I am really struggling here. Admittedly I am no guru especially when it comes to node and asynchronous programming, I am an old C# .net developer so I am comfortable with code but struggling here.
Here's the back story, short and sweet. I have a pg database and I am using the sequelize ORM tools to create a relatively simple CRUD app.
Here's what I want to do.
Make a call to the findAll function on one object.
I need a piece of information from that first call so that I can make a subsequent call.
For instance. Lookup the current user to get their details, grab their ID and now lookup their display preferences.
I know I can run two requests that are not linked using Promise.all, here is an example of this already working.
var delConfig = deliverabiltyConfigs.findAll2(req.signedCookies.tsUser);
var delPack = deliverabilityPackages.findAll2();
Promise.all([delConfig, delPack]).then((results) =>{
res.render('index', { title: 'Deliverability Calculator', UserEmail : req.signedCookies.tsUser, UserName : req.signedCookies.tsUserName, data:results[0], packs:results[1]});
});
Where I am stuck is passing data from one promise to then next and needing them to run asynchronously.
Please help!
There are a few way you can do this. Either use promise chaining or with async & await.
Promise chaining might be the simplest way to do this now, but I would suggest using async await as its easier to read. Since you didn't really provide a sample of what you were trying to do I will make something generic that should hopefully help.
So using promise chaining you would do something like:
pgConnection.findAll().then((data) => {
const foo = data.foo;
pgConnection.findSomething(foo).then((data2) => {
console.log(data2);
});
});
What is happening here is once the promise from findAll() is resolved successfully it will call the .then method and will pass the resulting data there for you to use in your next db query and then I am just printing out the result of the final db query.
This is how you could do it using async & await:
async function getFoo() {
const data = await pgConnection.findAll();
const foo = data.foo;
const data2 = await pgConnection.findSomething(foo);
console.log(data2);
}
The await keyword can only be used inside of an async function so it might not be as simple to change as just using a .then promise chain.

NestJs Async controller method vs calling await / async inside a method

I'm bit new to NodeJs & NestJs. I always wondered what's the difference between using async as the method return type inside a controller vs executing async operation inside a regular method ? How does NodeJs handles the request in both these cases if there is huge traffic on this API (eg. 40K req/min). Will it be blocking in the 2nd example and non blocking in the 1st or would it work in a similar way?
For Eg:
#Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
#Post()
async sample() {
return "1234";
}
}
vs
#Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
#Post()
function sample() {
return await methodX();
}
async function methodX(){
return "1234"
}
Please ignore what the content in sample() & methodX() does its only for example.
First, marking a method as async enables you to use the await keyword inside of it.
For example in the second sample you provided, you need to mark the method sample as async to await methodX:
#Post()
async function sample() {
// Now `await` can be used inside `sample`
return await methodX();
}
So to answer your questions
what's the difference between using async as the method return type inside a controller vs executing async operation inside a regular method ?
There is none. In both cases, the method of the controller will need to marked as async. Performing what the route is supposed to perform in the body of the method or extracting it in another async method is just a matter of code organisation.
Will it be blocking in the 2nd example and non blocking in the 1st or would it work in a similar way?
Both examples would work in a similar way.
Second, marking a mehthod as async doesn't actually make it async if there is no real async operation performed in its body like a request to another service or a setTimeout. It means that the following samples
// Sample 1
#Post()
async sample() {
return "1234";
}
// Sample 2
#Post()
function async sample() {
return await methodX();
}
async function methodX(){
return "1234"
}
Are both equivalent to the synchronous method
#Post()
syncSample() {
return "1234";
}
Finally, as stated by #Micael Levi, return await is syntactically correct but should be avoided. Considering this sample:
#Post()
function async sample() {
return await methodX();
}
async function methodX(){
throw new Error('something failed')
}
Because the method sample return await methodX, sample won't appear in the stack trace which makes debugging more difficult.
We would prefer this sample:
#Post()
function async sample() {
const result = await methodX();
return result;
}
async function methodX(){
throw new Error('something failed')
}

Refresh page while element is not presented with cucumber-nightwatch (selenium web driver)

I need to refresh page while element is not presented
i'm trying something like this, but it doesn't help
When(/^"([^"]*)" task status changed$/, taskName => {
let needRefresh = true;
do {
client.url(`${client.globals.env.url}${client.globals.env.index}/messaging/messages`)
.pause(10000)
.getTagName(`//div[contains(#class, "task-checkbox")]//*[contains(text(), "${taskName}")]`, res => {
client.equal(res.value, 'div')
}).pause(20000);
} while (!needRefresh)
});
how to do it correctly?
To be able to use complex asynchronous operations I suggest to use the new async functions. If your NodeJs version does not support it natively I suggest to use Babel. There is an example for that in the nightwatch-cucumber example folder. To be able to refresh the page until some condition you can use the following example.
When(/^"([^"]*)" task status changed$/, async (taskName) => {
let needRefresh = true;
do {
await client.refresh();
await client.pause(10000);
needRefresh = await client.getTagName(...
} while (!needRefresh)
});

nunit tests do not complete when testing async mvc5 controller (vs 2015)

I have an mvc 5 controller that makes use of some async data access code. I've written a simple test using nUnit. The test doesn't complete, it just spins until i cancel it. afaik i've set up the test correctly; it's awaiting the controller action is marked as async and returns a task. Am i missing something? Interestingly, the test works when i mock out the dependencies using moq, but if i go for an integration test with the actual dependencies in place, it just spins forever.
the a simplified test:
[Test]
public async Task Get_WhenProductHasData_ReturnsView()
{
// Arrange
...
// Act
PartialViewResult actualResult = await _controller.Widget(_productId1) as PartialViewResult;
// Assert
Assert.That(actualResult, Is.Not.Null);
...
}
And here's the simplified controller
public async Task<ActionResult> Widget(string productId)
{
ProductStats stats = await _statsService.GetProductStatsAsync(productId);
return PartialView(stats);
}
Try this instead:
[Test]
public async Task Get_WhenProductHasData_ReturnsView()
{
// Arrange
...
// Act
var result = await _controller.Widget(_productId1);
// Assert
Assert.That(result as PartialViewResult, Is.Not.Null);
}
Note that the "Act" line is simply awaiting and the result is then cast as a PartialViewResult on the Assert.That line, if it was null or not a PartialViewResult type it would return null. Either way you get what you're looking for.

Resources