繁体   English   中英

如何在async / await下重写一个函数?

[英]How to rewrite a function under async/await?

我想停止使用异步库,将其替换为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

我将实施的解决方案还包括bluebird 这是我将如何使用它。

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
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM