Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to a function using async/await

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.

like image 648
hidace Avatar asked Jul 17 '17 15:07

hidace


People also ask

Can async functions have parameters?

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.

Can I use async await for normal function?

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();

Can I use async await instead of promises?

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.

Can IIFE be async?

An async function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.


1 Answers

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.

like image 178
tiagodws Avatar answered Oct 25 '22 14:10

tiagodws