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

标签 javascript async-await ecmascript-2017

我想停止使用异步库,用 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
  })
}

关于javascript - 如何在 async/await 下重写一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46718800/

相关文章:

javascript - 使用正则表达式提取 url 路径

javascript - 在第三个 Controller 中使用时 RootScope 不工作

c# - 具有节流持续时间和批量消费的异步生产者/消费者

async-await - 使用 ES7 异步函数对 Sequelize 进行未处理的拒绝

Angular 8 Native Typescript 无崩溃,访问器简写

javascript - 如何在异步/等待语法中使用 Promise.prototype.finally()?

php - 推荐一个不错的非第三方简易聊天室

javascript - 无法使用 concat 将元素插入空数组

c# - Parallel.ForEach 和异步等待

reactjs - 当谷歌显示空白页面时获取 - Reactjs