[英]A value which executes an function returns a promise
I have this piece of code and in the 2nd function where i check the db if i log stuff inside the function it logs fine but if i assign a var and call the function as it returns a true of false i get a pending promise I have this piece of code and in the 2nd function where i check the db if i log stuff inside the function it logs fine but if i assign a var and call the function as it returns a true of false i get a pending promise
const mongoose = require('mongoose')
const config = require('./config.json')
const schema = require('./data')
const mongoactivate = async(config) => {
await mongoose.connect(config.mongo, {
useUnifiedTopology: true,
useNewUrlParser: true
})
}
mongoactivate(config)
const check = async(p, q) => {
let data = await schema.findOne({
username: p,
pass: q
})
let cor = (data === null) ? false : true;
console.log(cor)
}
const ans = check("p", "q")
console.log(ans)
You are in troubles with async/await.你遇到了异步/等待的麻烦。 You have to await first mongoactivate(config) and check('p', 'q') .您必须先等待mongoactivate(config)和check('p', 'q') 。 Try writing await before those functions.尝试在这些函数之前编写await 。
Good luck my g祝你好运我的g
You're not awaiting the mongoactivate()
function.你不是在等待mongoactivate()
function。 Async functions always return a Promise.异步函数总是返回 Promise。 Also, your check
function never returns anything, so ans
won't be the value you'd expect it to be.此外,您的check
function 永远不会返回任何内容,因此ans
不会是您期望的值。 Return the cor
variable at the end of the function.返回 function 末尾的cor
变量。
const mongoose = require('mongoose')
const config = require('./config.json')
const schema = require('./data')
const mongoactivate = async (config) => {
await mongoose.connect(config.mongo, {
useUnifiedTopology: true,
useNewUrlParser: true
})
}
const check = async (p, q) => {
let data = await schema.findOne({
username: p,
pass: q
})
let cor = (data === null) ? false : true;
return cor;
}
(async () => {
await mongoactivate(config)
const ans = await check("p", "q")
console.log(ans)
})()
you need to know how to work with await/async, JS is not like C# or C if you still have some issues with that i advice you to resolve the promise like in this exemple:你需要知道如何使用等待/异步,JS 不像 C# 或 C 如果你仍然有一些问题,我建议你解决 promise 像这个例子:
const Afunction = async(p,q)=> {
let ThePromise = new Promise((resolve,reject) => {
//resolve the pending promise that you got
let data = await schema.findOne({
username: p,
pass: q
})
let cor = (data === null) ? false : true;
resolve(cor)
})
return ThePromise.then(val=> {return val} )
}
And then you can get the result with:然后你可以得到结果:
const TheValueIwant = await Afunction ("p","q");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.