函数返回异步响应 [英] Function return async response

查看:101
本文介绍了函数返回异步响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜欢一个人在这里问(但他的解决方案,调用诺特尔功能) http://stackoverflow.com/a/10796326 / 315200 ......我想知道,如果它可能有不调用第二个函数的异步请求响应功能,而只是返回当异步请求响应。

Like a person asked here (but his solutions as to call a nother function) http://stackoverflow.com/a/10796326/315200 ...I would like to know if its possible to have a function which doesn't call a second function on response of an async request, but simply return when the async request responses.

事情是这样的,也许:

function callToFacebook() {
    var fbResponse;

    FB.api('/me', function (response) {
        fbResponse = response;
    });

    return fbResponse; //Will return undefined because CallToFacebook is async
}

这不是可能的一些方法,而不调用另一个函数??

Isn't that possible some way, without calling another function??

我试图做到的,是有一个功能,我可以用一些参数调用,这将返回响应对象从异步Web服务,像FB。

What I'm trying to achieve is to have one function I can call with some parameters, which will return the response object from a async webservice, like FB.

推荐答案

总之,没有。你不能有一个异步函数返回一个有意义的值同步,因为该值不当时存在(因为它是异步内置在背景中)。

In short, no. You cannot have an asynchronous function return a meaningful value synchronously, because that value does not exist at that time (as it is built asynchronously in the background).

您可以,但是,返回无极的对象,再presenting在潜在回报价值的异步操作,并绑定一个函数,该对象使用做()

You can, however, return a Promise object, representing the "potential return value" of the asynchronous operation, and bind a function to that object using done() or similar. That way, your function gets return semantics (instead of having to chain the control flow into a callback), and remains asynchronous.

这篇关于函数返回异步响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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