javascript:在.replace中进行异步/等待 [英] javascript : Async/await in .replace

查看:381
本文介绍了javascript:在.replace中进行异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下方式使用async/await函数

I am using the async/await function the following way

async function(){
  let output = await string.replace(regex, async (match)=>{
    let data = await someFunction(match)
    console.log(data); //gives correct data
    return data
  })
  return output;
}

但是返回的数据是一个Promise对象.只是对应该在带有回调的此类函数中实现它的方式感到困惑.

But the returned data is an promise object. Just confused about the way it should be implemented in such functions with callback.

推荐答案

一个易于使用和理解的异步替换功能:

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.

像这样使用它:

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

或者这个:

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

别忘了您的myAsyncFn必须返回承诺.

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

asyncFunction的示例:

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

这篇关于javascript:在.replace中进行异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆