从异步或同步的JavaScript要求返回值 [英] Return value from asynchronous OR synchronous JavaScript request

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

问题描述

第一下面的函数进行同步对比测试== 0 ,如果通过,返回一些内容,如果没有通过,执行异步请求。我的目的是为后来返回一些其他的内容,比如从东西后回调,但要知道我在做事情的方式是错误的。在不改变Ajax请求同步的,是有可能做到这一点?

The function below first performs a synchronous comparison test == 0, and if it passes, returns some content, and if it doesn't pass, performs an asynchronous request. My intent is for the later to return some other content such as "something from post callback", but know I am doing things way wrong. Without changing the Ajax request to synchronous, is it possible to do this?

var value = function (test) {
    if (test == 0) {
        return 'value is zero ';
    } else {
        return $.post('/echo/html/', {
            html: 'false ',
            delay: .5
        }, function (r1) {
            console.log('r1', r1);
            return 'something from post callback';
        })
            .done(function (r2) {
            console.log('r2', r2);
            return 'something from done callback';
        });
    }
}(1);

console.log(value);

https://jsfiddle.net/o5kq8he6/2/

推荐答案

既然你已经返回从AJAX调用一个承诺,那么从您的同步进行比较,只是返回一个解决的承诺。然后,这两个code路径返回与该终值和调用者可以使用同样的code到不管它的内部工作原理哪种方式处理结果解决的承诺。这是一种常见的设计模式为code,它有时是同步的,有时异步的。

Since you are already returning a promise from the ajax call, then from your synchronous comparison, just return a resolved promise. Then, both code paths return promises that are resolved with the terminal value and the caller can use the same code to process the result no matter which way it works internally. This is a common design pattern for code that is sometimes synchronous and sometimes asynchronous.

var myFunc = function (test) {
    if (test == 0) {
        return $.Deferred().resolve('value is zero ');
    } else {
        return $.post('/echo/html/', {
            html: 'false ',
            delay: .5
        }).then(function (r2) {
            console.log('r2', r2);
            // this will be the return value of the promise
            return 'something from ajax finished';
        });
    }
};

myFunc(1).then(function(value) {
    // value is here either way
});

仅供参考,它没有意义在你的 $。员额()来使用这两个成功的处理函数和一个 .done()处理程序。如果你打算从函数返回一个承诺(这是我的建议),那么你应该只使用承诺处理程序,而不是成功的回调。

FYI, it does not make sense in your $.post() to use both a success handler function AND a .done() handler. If you're going to return a promise from the function (which is my recommendation), then you should use only promise handlers, not the success callback.

您可能还需要明白,它没有任何用处,从Ajax调用成功处理程序返回一个值。该返回值只是去回到阿贾克斯基础设施的异步肠子,并且从未使用过任何事情。

You may also need to understand that it does nothing useful to return a value from the success handler of an ajax call. That return value just goes back into the asynchronous bowels of the ajax infrastructure and is never used by anything.

这篇关于从异步或同步的JavaScript要求返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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