从内回调Assing变量 [英] Assing variable from inner callback

查看:130
本文介绍了从内回调Assing变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的真实想法这个问题不重复,因为我知道如何使用回调作为链接的问题解释来解决它,这个问题是具体说明的情况下,我不能修改outfer功能,这是不是涵盖了另一个问题

我用,我不能修改,库库做这样的事情:

I use a library that I cannot modify, the library do something like this:

VAR的结果=美孚()

然后使用结果的工作。我不能修改如何结果的作品,我只能修改,因为我把它作为参数传递给库。

Then it uses result for the work. I can not modify how result works, I can only modify Foo because I pass it as parameter to the library.

如果有这样的事情

funcion Foo(){
  return "Hello"
}

它可以完美运行。结果是您好和它的作品。

问题是,我的有里面的异步调用。它调用一个Web服务器,然后它应该返回的服务器的响应。因此,

The issue is that my Foo has an async call inside it. It calls a web server and then it should return the response of the server. So

funcion Foo(){
   request.get('http://server.com', function(error, response, body){
      var parsed = JSON.parse(body);
      return parsed.Hello;
   });
}

在此情况下,当 VAR的结果=美孚(); 结果不包含服务器的响应(因为是异步),并继续一个空的结果。

In this case when var result = Foo();, result does not contains the response of the server (because is async) and continue with an empty result.

所以,如果我只能修改我应该怎么办?

So if I only can modify Foo what should I do?

更新:如果你没有发现它可能我很想听到像什么,我应该在公关索要库,还是有办法迫使其要求的替代品syncronous

推荐答案

这是如何通过一个同步请求工作:

This is how you can work with a synchronous request:

funcion Foo(){
   var request = new XMLHttpRequest();
   request.open("GET", "http://server.com", false);
   request.send();
   function handleResponse(response) {
      console.log(response);
   }
   handleResponse(request.responseText);
}

如果你只能修改,然后修改它同步发送请求。

If you can only modify Foo, then modify it to send the request synchronously.

这篇关于从内回调Assing变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆