Syntax for an Async Arrow Function

Syntax for an async arrow function

Async arrow functions look like this:

const foo = async () => {
// do something
}

Async arrow functions look like this for a single argument passed to it:

const foo = async evt => {
// do something with evt
}

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}

The anonymous form works as well:

const foo = async function() {
// do something
}

An async function declaration looks like this:

async function foo() {
// do something
}

Using async function in a callback:

const foo = event.onCall(async () => {
// do something
})

Using async method inside of a class:

async foo() {
// do something
}

How to call an async arrow function with await

const getName = async () => await Promise.resolve('John');

In the above, you have an async function (the arrow function) which uses await inside.

This is fine (albeit pointless as you could return the promise directly).

Here:

const name = await getName();

You use await again, and while the function on the right-hand side does return a promise, the function it appears inside is not async so it is not valid.


Put it inside an async function and it will be fine:

const getName = async() => await Promise.resolve('John');
const init = async() => { const name = await getName(); console.log(`Hi ${name}`);};
init();

How do you create a named async arrow function?

Arrow functions have no name, but you can assign them to a variable like this:

const normalFunc = () => { ... };
const asyncFunc = async () => { ... };

Do note, however, that arrow functions are not just shorter notation for regular functions, as there are some subtle differences to be aware of (see this article for details). However, if you understand these differences and they don't affect your code, you should be fine.

How to make arrow function async?

You can make fat arrow function async using the syntax below.

const asyncFunc = async () => {
const result = await someAsyncFunc();
}

TypeScript Async/Await Arrow Function: Right Syntax (in React)

@VLAZ found the error and explained it well in the comments.
I still wanted to post a version with the new changes.

I changed the first block of code to:

compareValues: = async () => {
try {
const value1 = false;
const value2 = this.getValue2;

const isEqual = (await value2) === value1;
return isEqual;
} catch (error) {
throw error;
}
}

Reason (explained in the comments): compareValues holds a function that will produce a promise when called. It's not an actual Promise itself.

Chai testing await/async arrow function with parameters

@jonrsharpe's suggestion is correct,
chai-as-promised will do this. I give you a fully working example.

Chai as Promised extends Chai with a fluent language for asserting facts about promises.

import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

class InvalidInviteException extends Error {}

export const createInviteDomainOwner = () => {
const inviteDomainOwner = async ({ emailAddress, firstName, lastName, domainId }) => {
try {
throw new InvalidInviteException('This is not a valid invite.');
} catch (e) {
throw e;
}
};

return {
inviteDomainOwner,
};
};

it('invite domain owner', async function () {
const { inviteDomainOwner } = createInviteDomainOwner();

await expect(
inviteDomainOwner({
emailAddress: 'abc123abc@test.com',
firstName: 'John',
lastName: 'Doe',
domainId: '1111-1111-1111-1111',
}),
).to.eventually.rejectedWith(InvalidInviteException, 'This is not a valid invite.');
});
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",

Array.filter() with async arrow function

filter expects the return value of the callback to be a boolean but async functions always return a promise.

You don't know if you want to return true or false in time to tell filter which it is.

What you possibly want to do is:

  1. map the data from data to { keep: true, original_data: data } (using an async callback)
  2. Pass the resulting array of promises to Promise.all
  3. await the return value of Promise.all
  4. filter that array with: .filter(data => data.keep)
  5. Get the original objects back with .map(data => data.original_data)

Something along these lines (untested):

const filterWithEmail = (
await Promise.all(
data.map(async (data) => {
const findUser = await UserService.findUser(doc.id).catch((err) => {});
let keep = false;
if (findUser && regexFilter)
keep = regexFilter.test(email.normalize("NFKC"));
return { data, keep };
})
)
)
.filter((data) => data.keep)
.map((data) => data.data);

Unexpected token when using arrow function for firebase functions

I have tested this and I confirm that there are two things you definitely need, to fix the issue you are facing, would be to change in your package.json the scripts section to the following:

"scripts": { "lint": "eslint", ... } instead of “scripts”: {“lint”:”eslint .”, …} which is default.
So, removing the . from there, which is auto-generated but might cause this kind of issues.

Arrow functions are an ES6 feature, but here you have an async arrow function.
Async functions in general are an ES8 (or 2017) feature. Therefore you need to specify the change the ecmaVersion of the parser to version 8, so changing in your .eslintrc.js file to this:

parserOptions: { parser: 'babel-eslint', ecmaVersion: 8, },

This will let the parser know to expect the => token after async is used.



Related Topics



Leave a reply



Submit