在javascript中制作同步功能? [英] Make synchronous function in javascript?

查看:184
本文介绍了在javascript中制作同步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像jQuery的 $。ajax({..,async:false,..});

I wanna synchronized functions just like jQuery's $.ajax({ .., async: false, .. });.

function A() { lalala .. };
function B() { dadada .. };
function C() { .. };

,这些都包括fadeIn,Out,slide等等。

, those all including some effect like fadeIn, Out, slide... etc.

但我刚发现这些函数如下所示:

However I just found if those functions called like below..

A();
B();
C();

所有效果几乎同时开始。根据我的理解,这是因为函数同步调用但并不意味着函数B()在函数A()完全完成后启动..对吗?

All effect start at almost same time. In my understanding, this happens because the function called synchronously but it doesn't mean that function B() started after function A() was completely finished.. right?

然后,我怎样才能使这些函数按顺序工作?

Then, how can I make those functions work in order?

我找到了一种使用回调函数的方法,但这对我来说还不够..

I found a way use callback function but it's not enough for me..

推荐答案

查看使用 jQuery $ .Deferred();

这可以让你按顺序运行每个函数,一个等待在另一个之后。例如:

That can allow you to run each function in sequence, one waiting after the other. For example:

var a = function() {
    var defer = $.Deferred();

    console.log('a() called');

    setTimeout(function() {
        defer.resolve(); // When this fires, the code in a().then(/..../); is executed.
    }, 5000);

    return defer;
};

var b = function() {
    var defer = $.Deferred();

    console.log('b() called');

    setTimeout(function () {
        defer.resolve();
    }, 5000);

    return defer;
};

var c = function() {
    var defer = $.Deferred();

    console.log('c() called');

    setTimeout(function () {
        defer.resolve();
    }, 5000);

    return defer;
};

a().then(b).then(c);

使用 defer.resolve(); 表示你可以控制函数何时执行下一个函数。

Using defer.resolve(); means you can control when the function yields execution to the next function.

这篇关于在javascript中制作同步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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