假设我有一个简单的 JavaScript 函数:
function someFunction(integer)
{
data = integer + 1;
return data;
}
我需要从另一个函数内部调用它并使用返回值:
function anotherFunction(integer)
{
int_plus_one = someFunction(integer);
//Do something with the returned data...
int_plus_two = int_plus_one + 1;
return int_plus_two;
}
如何确保 anotherFunction return 的返回值仅在 someFunction 完成后才返回?实际上,它似乎可以与这些非常快速的函数一起使用。但是,如果 someFunction 必须执行一些 ajax 查找,则 aotherFunction 的返回将失败。
谢谢, 史蒂夫
最佳答案
您不知道异步函数何时或是否会完成。处理此问题的唯一方法是使用回调函数,该函数在异步操作完成后执行。
这是我的“啊哈!”时刻:How to return the response from an asynchronous call?
关于javascript - 函数完成后运行代码并获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761898/