等待/异步在匿名函数中的使用

14

我试图在匿名函数上使用await,这是结果:

以下是可行的方式。

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

结果:

"你好"

这是我希望它工作的方式:

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

结果:

[AsyncFunction]

我错过了什么吗?我对 Promise 很新。

编辑: 我尝试在匿名函数后面添加 () 来调用它。这里是使用实际 Async 代码的示例:

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

console.log的结果:

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

res.code的结果:

handledPromiseRejectionWarning: TypeError: Converting circular structure to JSON

我认为错误不是来自models.usersModel.findOneInvitationByToken,因为在第一个情况下使用它时它可以正常工作。

let userFound = await test(invitationToken, email);

编辑2:

我找到了第二个问题!我忘记将参数放入括号中。

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

结果:

{ oki: {mydata} }


1
你为什么在同步函数上使用async/await? - Andrew Li
1
在第二段代码片段中,你只是声明了这个函数,但是你没有调用它。 - Nir Alfasi
@alfasin,我怎么在同一行调用它? - Bidoubiwa
2
我建议您提出一个单独的问题来解决这些无关的问题,或者如果您需要交互式调试帮助,则可以开始聊天会话。希望您对等待匿名函数的问题有所回答。 - Jacob
1
我认为应该有更简单的方法来解决它,但或许我们只需要链接到一个聊天室?!https://chat.stackoverflow.com/rooms/17/javascript - Jacob
显示剩余9条评论
2个回答

34

你要等待从异步函数中返回Promises,而不是等待异步函数本身。只需添加一个调用即可:

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

我尝试了一下,现在我的console.log返回一个serverResponse对象。我将编辑我的帖子。 - Bidoubiwa
@Couteau 这就是为什么你要在问题中放置实际的异步代码,而不仅仅从异步函数返回一个字符串(这本来就不应该做)。 - Andrew Li
2
如果您使用fetch,则应该会得到一个serverResponse。如果您想要下载响应的内容,则需要调用其.json()或类似的方法,并等待它。 - Jacob
在Node.js上使用会导致:ReferenceError: await未定义。 - Kirill
@Sososlik 或许是针对旧版本的 Node.js。自 7.6 版本起,已经支持 await。由于您的版本可能不支持顶级 await,因此在 REPL 中也可能会看到这一点。 - Jacob
@Jacob,问题是因为我没有将当前函数声明为“async”。在这种情况下,错误描述很令人困惑。 - Kirill

4

在第二种情况下,您没有调用函数:

let x = await hello();

在第一种情况下,您是这样访问它的,但在第二种情况下,您只是将等待添加到函数声明中。它只返回函数,您需要将其更改为

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

我尝试过了,现在我的console.log返回一个serverResponse对象。我会编辑我的帖子。 - Bidoubiwa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接