0.4.1 • Published 8 years ago

@zkochan/async-replace v0.4.1

Weekly downloads
113
License
MIT
Repository
github
Last release
8 years ago

@zkochan/async-replace

String replace using asynchronous replacement functions

Build status NPM version

Motivation

"All I needed" was a simple function to do string.replace(/regex/, callback), so that I could find some matches in a url and call my own custom function to return the value to be replaced back into the string. Sounds pretty easy right? It is, as long as your callback function is syncrhonous. :)

What happens if you need to call an asychronous function to determine the replacement value(s)? Perhaps you are using the match value to lookup a record in a database. In my case, I needed to perform DNS SRV record lookups to replace hostnames with the returned host:port combination.

Installation

This module is installed via npm:

npm install @zkochan/async-replace --save

Usage

'use strict'
const asyncReplace = require('@zkochan/async-replace')

asyncReplace('String with regex to replace', /regex/g, (match, offset, str, cb) => {
  setTimeout(() => {
    const replacementValue = match.split('').reverse().join('')
    const err = null
    cb(err, replacementValue)
  }, 1000)
}, (err, finalResult) => {
  if (err) {
    console.log('Error - ' + err)
  } else {
    console.log(finalResult)
    //> String with xeger to replace
  }
})

The same result can be achieved using promises:

asyncReplace('String with regex to replace', /regex/g, (match, offset, str) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const replacementValue = match.split('').reverse().join('')
      resolve(replacementValue)
    }, 1000)
  })
})
.then((finalResult) => console.log(finalResult))
//> String with xeger to replace
.catch((err) => console.log('Error - ' + err))

NOTE: In this particular example, the gratuitous use of setTimeout is just to demonstrate the asynchronous functionality in the replacement callback.

License

MIT © Phillip Markert


Dependencies

  • babel-run-async: Utility method to run function either synchronously or asynchronously using the common this.async() style.
  • babel-runtime: babel selfContained runtime