I'm trying to pass arguments to a function that uses async/await. I've defined my function like so
// common.js
export const myAsyncFunc = async (t, textA, textB) => {
await t
.typeText('#input-1', textA)
.typeText('#input-2', textB);
};
However, when I try to import this function to another file, like so, I can't pass it t
because t is not defined
:
// index.js
import { myAsyncFunc } from './common'
myAsyncFunc(t, textA, textB)
Is it possible to just pass in my textA
and textB
arguments (possibly with currying or another way) with async/await?
EDIT: So this is being run as part of the test cafe library. It looks like t
comes from when testcafe chrome client/__tests__/
is run, rather than being imported in the common.js
file.
The async method can't declare any in, ref or out parameters, nor can it have a reference return value, but it can call methods that have such parameters.
You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so. function caller() { // Using await in a non-async function. const user = await fetchUserDetails(); } // This will result in an syntax error caller();
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
An async function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.
You are importing/exporting myAsyncFunc
, but in your code you are calling myAsyncFunction
.
Also, you are chaining
.typeText('#input-1', textA)
.typeText('#input-2', textB);
But I think .typeText
returns a promise, right? So you should:
export const myAsyncFunc = async (t, textA, textB) => {
await t.typeText('#input-1', textA);
await t.typeText('#input-2', textB);
};
Other than that, the code is working just fine, assuming you defined t
somewhere, as pointed out in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With