I’ve learned javascript async/await before learning promise.then() syntax, and I am now attempting to go back and learn promise.then().
I currently have the following code
let getDatabaseData = async () => {
let res1 = await dbQuery()
let res2 = await dbQuery2(res1)
return res1 + res2
}
let dbData = await getDatabaseData()
console.log(dbData)
I want to translate this to promises, and have done so below
let getDatabaseData = () => {
return new Promise(resolve => {
dbQuery().then(res1 => {
dbQuery2(res1).then(res2 => {
resolve(res1 + res2)
})
})
})
}
getDatabaseData().then(dbData => {
console.log(dbData)
})
Is this the most effective way to do so? I was looking into promise chaining, but it doesn’t exactly get me what I want because I want getDatabaseData to act as a helper method to combine the results from dbQuery and dbQuery2
2
Answers
Your code most directly translates (to me) to:
Another option without using the enclosing fn’s scope could look like this:
Remember, any time you’re using the
new Promise(...)
syntax, and calling proimse-generating functions inside that promise, you’re probably doing something that could be better accomplished with promise chaining.You can do it without the need for creating an extra variable or using
Promise.all()
if you simply nest the dbQueries using the.then()
method:This gives me full access to the results from both queries in a local scope under the objects
p
(post) andu
(user).