[removed] Async/await in .replace

前端 未结 4 1312
情话喂你
情话喂你 2021-02-05 06:00

I am using the async/await function the following way

async function(){
  let output = await string.replace(regex, async (match)=>{
    let data = await someF         


        
4条回答
  •  遥遥无期
    2021-02-05 06:10

    An easy function to use and understand for some async replace :

    async function replaceAsync(str, regex, asyncFn) {
        const promises = [];
        str.replace(regex, (match, ...args) => {
            const promise = asyncFn(match, ...args);
            promises.push(promise);
        });
        const data = await Promise.all(promises);
        return str.replace(regex, () => data.shift());
    }
    

    It does the replace function twice so watch out if you do something heavy to process. For most usages though, it's pretty handy.

    Use it like this:

    replaceAsync(myString, /someregex/g, myAsyncFn)
        .then(replacedString => console.log(replacedString))
    

    Or this:

    const replacedString = await replaceAsync(myString, /someregex/g, myAsyncFn);
    

    Don't forget that your myAsyncFn has to return a promise.

    An example of asyncFunction :

    async function myAsyncFn(match) {
        // match is an url for example.
        const fetchedJson = await fetch(match).then(r => r.json());
        return fetchedJson['date'];
    }
    
    function myAsyncFn(match) {
        // match is a file
        return new Promise((resolve, reject) => {
            fs.readFile(match, (err, data) => {
                if (err) return reject(err);
                resolve(data.toString())
            });
        });
    }
    

提交回复
热议问题