1.0.5 • Published 6 years ago

async-replace-es6 v1.0.5

Weekly downloads
19
License
MIT
Repository
github
Last release
6 years ago

Run replace on a string with an asynchronous function (promises).

Usage

async-replace-es6 has the same api as String.prototype.replace. Only the callback is an async function.

This is usefull if you need the matched part of a string before running an asynchronous operation.

import { replace } from 'async-replace-es6';
const { replace } = require('async-replace-es6');
const replaced = await replace(originalString, /someregex/g, asyncReplacer);

Or

replace(originalString, /someregex/, asyncReplacer)
    .then(replaced => console.log(replaced));

Example of asynchronous replacer :

async function asyncReplace(match, group1, group2, ...) {
    // here match is an url
    const response = await fetch(match);
    const json = await reponse.json();
    return json['title'];
}

function asyncReplacer(match, ...groups) {
    // match is a file path
    return new Promise((resolve, reject) => {
        fs.readFile(match, (err, data) => {
            if (err) {
                return reject(err);
            }
            resolve(data.toString());
        });
    });
}

If your promises need to be done Sequentially here is a solution:

const { replaceSeq } = require('async-replace-es6');

replaceSeq(originalString, /someregex/g, asyncReplacer)
    .then(replaced => console.log(replaced));
1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago