I'm using Sequelize in an Express app, and I cannot figure out how to use console.log() in a async
function. Whenever I want to printout a fetched instance from db, the console log halts the execution.
This is what I've tried (each example in separate tries):
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
},
I've as well with 0 success tried the following:
const user = await User.findById(3).then(user => {
console.log('user: ', user)
})
Assuming the User
object returns a promise, try the following:
updateUser: async (_, { id, ...args }, { User }) => {
const user = await User.findById(3)
console.log('user: ', user)
return user
}
console.log
stops nothing, await
does
This will stop execution until User
has found something :
const user = await User.findById(3).then(user => {
console.log('user: ', user)
})
As will this until aFunction
has a response :
const user = await aFunction(anArg).then((do) => something);
What you want to do is :
var value; // have this somewhere or something similar
aFunction(anArg).then((res) => { value = res; })
Or in your case :
var savedUser; // have this somewhere or something similar
User.findById(3).then((user) => { savedUser = user; console.log('user: ', user); })
With using the await
you are actually telling the javascript engine to stop till the promise is resolved.
Update code
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
},
For more on the async await - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.