Warm tip: This article is reproduced from stackoverflow.com, please click
async-await asynchronous es6-promise javascript node.js

Await / async on anonymous function

发布于 2020-03-27 10:29:37

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} }

Questioner
Couteau
Viewed
73
2,123 2018-08-03 01:02

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