您好,我有以下代码:
function outer() {
try {
ScriptLoader.getScripts('proj4script',proj4Callback);
}
catch(e) {console.log(e);}
function proj4Callback() {
x = proj4(some geo coord calcs here);
}
// I need access to the values stored in x here
}
从代码中可以看到,我使用脚本加载器将proj4脚本加载到环境中。不幸的是,此脚本加载器没有返回值。脚本加载器的参数之一是回调函数-该函数不能接受任何参数。
我正在尝试访问我在外部函数中的回调函数内部计算的数据。我有没有办法在外部函数之外不使用全局变量呢?
编辑:
@Trinot我不确定继续异步调用模式的含义,您的意思是这样的:
function main() {
x = await new Promise(outer());
}
async function outer().then({
await new Promise(ScriptLoader.getScripts.bind(ScriptLoader, 'proj4script'));
let x = proj4(/*some geo coord calcs here*/);
return x;
})
您需要接受回调的异步性质。因此,您不应尝试以同步方式进行编码。将需要的代码x
放在回调中,或从该回调中调用传递x
给另一个函数的函数,等等。无论您做什么,都需要从该回调中继续执行。
现在,有另一种现代的方法可以解决此问题:分配getScript
方法,并使用async
/ await
:
async function outer() {
await new Promise(ScriptLoader.getScripts.bind(ScriptLoader, 'proj4script'));
let x = proj4(/*some geo coord calcs here*/);
console.log(x);
return x;
}
这将中断函数执行,直到该getScripts
方法调用回调(在本例中为Promise解析器)为止。调用后,执行将在await
语句之后执行,并且可以访问您需要计算的变量x
。
但是请注意,调用 的代码outer
将在脚本加载之前继续执行。如果您还有依赖于已加载脚本的代码,则必须将then
方法链接到outer
调用,或将该代码也放置在async
/await
构造中。
假设您return x;
使用上述功能,这就是它的外观:
async function main() {
let x = await outer();
// rest of code that depends on the loaded script
}
main();
// Don't put anything here that needs the loaded script, as it will execute sooner.
要不然:
outer().then(function (x) {
// rest of code that depends on the loaded script
}
// Don't put anything here that needs the loaded script, as it will execute sooner.
注意:您可以像将其包装一样将其包装await
在一个try
块中,但是可以catch
在该outer()
调用上绑定一个方法调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句