Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await / async on anonymous function

I'm trying to use await on an anonymous function here are the results :

This is the way that works

async function hello(){
    return "hello";
}
let x = await hello();
console.log(x);

result :

"Hello"

This is the way i want it to work :

let x = await async function() {return "hello"};
console.log(x);

result :

[AsyncFunction]

What am i missing ? I'm new to promises.

EDIT : I tried adding the () after the anonymous function to call it. Here is the example with the actual Async code :

let invitationFound = await (async function (invitationToken, email){
    return models.usersModel.findOneInvitationByToken(invitationToken, email)
        .then(invitationFound => {

            return  invitationFound;
        })
        .catch(err =>{
           console.log(err);
        });
})();

console.log(invitationFound);
return res.status(200).json({"oki " : invitationFound});

Result of the console.log :

ServerResponse { domain: null, _events: { finish: [Function: bound resOnFinish] }, _eventsCount: 1, _maxListeners: undefined, output: [], outputEncodings: [], .....

Result of the res.code..

handledPromiseRejectionWarning: TypeError: Converting circular structure to JSON

I don't think the error come from models.usersModel.findOneInvitationByToken because it works fine when i use it in the first case

let userFound = await test(invitationToken, email);

EDIT 2 :

I found out the second problem ! I forgot to put the parameters into the parenthesis

let invitationFound = await (async function (invitationToken, email){
    return models.usersModel.findOneInvitationByToken(invitationToken, email)
        .then(invitationFound => {

            return  invitationFound;
        })
        .catch(err =>{
           console.log(err);
        });
})(invitationToken, email);

console.log(invitationFound);
return res.status(200).json({"oki " : invitationFound});

result :

{ oki : {mydata} }

like image 750
Bidoubiwa Avatar asked Aug 02 '18 16:08

Bidoubiwa


People also ask

Can anonymous functions be async?

Description. An async function expression is very similar to, and has almost the same syntax as, an async function statement . The main difference between an async function expression and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions.

Can you await an async function?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.

Can function be async without await JavaScript?

Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.


2 Answers

You await Promises, which are returned from async functions, not the async function itself. Just add a call:

let x = await (async function() {return "hello"})();
console.log(x);
// or
console.log(await (async() => 'hello')())
like image 55
Jacob Avatar answered Oct 31 '22 02:10

Jacob


You are not calling a function in the second case:

let x = await hello();

This is how you are accessing it in the first case but in the second case, you are just you are adding await to a function declaration. It is just returning function, you need to change it to

let x = await (async function() {return "hello"})();
console.log(x);
like image 38
Sandip Nirmal Avatar answered Oct 31 '22 01:10

Sandip Nirmal