替换功能内的异步加载 [英] Async load inside replace function

查看:38
本文介绍了替换功能内的异步加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Javascript 进行替换.我做了这样的事情:

I am working with replacements in Javascript. I did something like this:

var replacedText = originalText.replace(regex, function(value, i) { 
    return value + 'some_additional_data';
});

return replacedText;

但是现在我需要在 replace 方法中加载一个 HTML 模板.load方法是这样调用的:

But now I need to load a HTML template inside the replace method. The load method is called in this way:

res.render(location, json, function(error, html) {
    //i have the html loaded with my json data
});

我需要在我的替换方法中加载它,但我无法做到:

I need to load it inside my replace method, but I am unable to do it:

var replacedText = originalText.replace(media, function(value, i) {
    var json = buildJSON(value);
    res.render(location, json, function(error, html) {
        //how could i return the "html" object for the replace function?
    });
});

我尝试过类似的方法,但没有奏效:

I have tried something like this, but it didn't work:

var replacedText = originalText.replace(media, function(value, i) {
    var json = buildJSON(value);
    return res.render(location, json, function(error, html) {
        return html;
    });
});

任何帮助将不胜感激预先非常感谢您

Any help would be appreciated Thank you very much in advance

推荐答案

当您有一个需要同步返回值的回调时,您不能在该回调中使用异步操作来获取该值.异步操作(根据定义)将在回调返回后的某个时间完成,因此异步操作的结果无法从回调返回,并且无法让 JS 等待异步操作.

When you have a callback that demands a synchronous return value, you cannot use an async operation inside that callback to get that value. The async operation (by definition) will finish sometime later AFTER the callback has returned so the results of the async operation are just not available to return from the callback and there is no way to make JS wait for an async operation.

我没有完全按照您的代码尝试执行的操作,但是从您的话来看,听起来您想加载一个 HTML 模板并在替换操作中使用它.有一些不同的方法可以解决这个问题.

I don't follow exactly what your code is trying to do, but judging from your words, it sounds like you want to load an HTML template and use that in the replace operation. There are some different ways to approach that problem.

例如,您可以通过两次传递来完成此操作.

For example, you could do this with two passes.

  1. 第一遍实际上并没有改变你的字符串,它只是构建了一个需要的模板列表.

  1. The first pass doesn't actually change your string, instead it just builds a list of templates that are needed.

然后,您加载该列表中的所有模板.

Then, you load all the templates in that list.

然后,当您需要的所有模板都加载完毕后,您就可以进行替换,使用已加载的模板进行您计划的同步替换.

Then, when all the templates you will need are loaded, you can then do your replace, using the already loaded templates to do the synchronous replacement you planned.

这篇关于替换功能内的异步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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