skip to Main Content

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


  1. Your code most directly translates (to me) to:

    let getDatabaseData = () => {
        // we can store intermediate values in the closure if we want
        let val1;
        return dbQuery().then(val => {
            val1 = val;
            return dbQuery2(val);
        }).then(val2 => val1 + val2)
    }
    
    getDatabaseData().then((data) => console.log(data))
    

    Another option without using the enclosing fn’s scope could look like this:

    let getDatabaseData = () => dbQuery()
          // here, we use Promise.all to proxy values forward
          // in the resultant promise
          .then(val => Promise.all([val, dbQuery2(val)]))
          .then(([val1, val2]) => val1 + val2)
    

    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.

    Login or Signup to reply.
  2. 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:

    // I am setting up a testing scenario here:
    const url="https://jsonplaceholder.typicode.com/",
      dbQuery=id=>fetch(`${url}posts/${id??1}`).then(r=>r.json()),
      dbQuery2=id=>fetch(`${url}users/${id??1}`).then(r=>r.json()),
    
    
    // This is the actual function:
      getDatabaseData = pid =>
       dbQuery(pid).then(p =>
         dbQuery2(p.userId).then(u =>
           `Post ${p.id}:"${p.title}" by ${u.name}`
         )
       );
    
    // Now, test the function in an async IIFE:
    (async ()=>
      console.log(await getDatabaseData(1+Math.floor(100*Math.random())))
    )();

    This gives me full access to the results from both queries in a local scope under the objects p (post) and u (user).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search