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

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

问题描述

我在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;

但现在我需要加载的替代方法中一个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;
    });
});

任何帮助将是AP preciated
非常感谢你提前

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.

我不明白到底是什么你的code正在试图做的,但是从你的话来看,这听起来像你想加载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天全站免登陆