gpt4 book ai didi

javascript - 从其他函数中返回 Javascript 值

转载 作者:行者123 更新时间:2023-11-28 15:49:48 26 4
gpt4 key购买 nike

所以我想从一个函数中返回一个字符串,该函数由两次 AJAX 调用形成。我可以想出一种困惑的方法来做到这一点,但我想有更好的方法吗?

function fetchAndFillTemplate(options) {
$.getJSON(options.data, {}, function(data, status) {
$.get(options.template, function(template) {

// this is the string I want to return when you call 'fetchAndFillTemplate'
var rendered_template = Mustache.to_html(template, data);

});
});
}

最佳答案

您无法返回该值,因为它是一个异步任务。

不使用 Promise 的解决方法是:

function fetchAndFillTemplate(options, callback) {
$.getJSON(options.data, {}, function(data, status) {
$.get(options.template, function(template) {

// this is the string I want to return when you call 'fetchAndFillTemplate'
var rendered_template = Mustache.to_html(template, data);
callback(rendered_template);
});
});
}

如您所见,我们添加了一个新参数callback,它将是一个函数

那么,不要像这样调用:

var tpl = fetchAndFillTemplate(options);

你必须这样做:

fetchAndFillTemplate(options, function(rendered_template){
var tpl = rendered_template;
});

希望这有帮助。干杯

PS:嗯,有一种方法可以通过 ajax 调用 sync 来返回最终值,但我不会发布它,因为根本不推荐它(阻塞 UI)。

关于javascript - 从其他函数中返回 Javascript 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com