Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite a function under async/await?

I want to stop using the async library, replacing it with vanilla js.

const async = require('async')

function getTopicsData(tids, Uid, callback) {
  async.map(tids, (tid, next) => {
    redis.hgetall(`topic:${tid}`, (err, topics) => {
      redis.sismember(`topic:${tid}:subscribers`, Uid, (err, subscriber) => {
        topics.subscriber = !!subscriber

        next(false, topics)
      })
    })
  }, callback)
}

module.exports = getTopicsData
like image 666
NCHAryON Avatar asked Nov 18 '25 12:11

NCHAryON


1 Answers

The solution I would implement would also include bluebird. Here is how I would use it.

const Promise = require('bluebird')

const hgetall = Promise.promisify('redis.hgetall')
const sismember = Promise.promisify('redis.sismember')

module.exports = async function (tids, Uid) {
  return Promise.map(tids, async function (tid) {
    let {topics, subscriber} = await Promise.props({
      topics: hgetall(`topic:${tid}`),
      subscriber: sismember(`topic:${tid}:subscribers`, Uid)
    })

    topics.subscriber = !!subscriber

    return topics
  })
}
like image 131
InternalFX Avatar answered Nov 21 '25 03:11

InternalFX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!