本文介绍了异步函数中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了返回一些变量的函数。但我的函数异步使用另一个函数。

I've built the function to return some variable. But my function uses another function asynchronously.

function getVariable() {
  var myVariable;
  asyncronousFunction(function(...){

    myVariable = ...

  });
  return myVariable;
}

问题是 myVariable 之外和内部asyncronousFunction 是不同的变量。所以我不能从异步函数赋值给 myVariable

The problem is that myVariable outside of and inside in asyncronousFunction are different variables. So I can't assign value to myVariable from asynchronous function.

如何解决这个范围问题?谢谢。

How to resolve this scope problem? Thanks.

推荐答案

它们是相同的变量,但你不能返回 getVariable 函数同步调用异步函数的结果。 myVariable 的值将在稍后某个未指定的时间点异步更新。但是你的函数正在返回值 now 。这不起作用。

They are the same variable, but you cannot return the result of an asynchronous function call synchronously from your getVariable function. The value of myVariable will be updated asynchronously at some unspecified later point in time. But your function is returning the value now. That doesn't work.

这意味着你的 getVariable 函数也是异步的,这意味着你必须设计就这样。例如,它可以接受回调,就像 asyncronousFunction 那样。

That means your getVariable function is asynchronous as well, which means you have to design it that way. For example it could accept a callback, just like asyncronousFunction does.

这篇关于异步函数中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:38
查看更多