我在Express应用程序中使用Sequelize,但我不知道如何在async
函数中使用console.log()。每当我要从db打印出获取的实例时,控制台日志都会暂停执行。
这是我尝试过的方法(每个示例分别尝试):
updateUser: async (_, { id, ...args }, { User }) => {
const user = await User.findById(3)
// will later do some update to user here
await Promise.resolve(console.log('user: ', user)) // halts the execution
Promise.resolve(console.log('user: ', user)) // halts the execution
await console.log('user: ', user) // halts the execution
console.log('user: ', await user) // halts the execution
console.log('user: ', user) // halts the execution
console.log('only a string') // works!
return user
},
我也成功了0次,尝试了以下方法:
const user = await User.findById(3).then(user => {
console.log('user: ', user)
})
答案 0 :(得分:0)
假设User
对象返回一个Promise,请尝试以下操作:
updateUser: async (_, { id, ...args }, { User }) => {
const user = await User.findById(3)
console.log('user: ', user)
return user
}
答案 1 :(得分:0)
await
什么也没停止,User
可以
这将停止执行,直到const user = await User.findById(3).then(user => {
console.log('user: ', user)
})
找到了一些东西:
aFunction
在const user = await aFunction(anArg).then((do) => something);
之前,都会如此:
var value; // have this somewhere or something similar
aFunction(anArg).then((res) => { value = res; })
您想要做的是:
var savedUser; // have this somewhere or something similar
User.findById(3).then((user) => { savedUser = user; console.log('user: ', user); })
或者您的情况:
<td>
<div class="d-inline">
<%=rs.getString(4)%>
<a class="btn btn-success" href="" role="button">Edit</a>
<a class="btn btn-success" href="" role="button">Delete</a>
<!-- <a class="btn btn-danger" href="../src/java/Login.java" role="button">Approve</a>-->
<form method="post" action="" class="d-inline">
<input type="submit" value="submit" class="btn btn-danger">
</form>
</div>
</td>
答案 2 :(得分:-1)
实际上,您使用await
告诉javascript引擎停止运行,直到兑现承诺。
更新代码
updateUser: async (_, { id, ...args }, { User }) => {
const user = await User.findById(3)
// will later do some update to user here
Promise.resolve(console.log('user: ', user)) // halts the execution
console.log('user: ', user) // halts the execution
console.log('only a string') // works!
return user
},
有关异步等待的更多信息-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function