JavaScript的:后调用另一个函数的回调函数返回 [英] javascript: calling a function after another function's callbacks are returned

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

问题描述

这是我的问题的简化版本:

This is the simplified version of my problem:

var callback_one = function (result_from_web_service) {
  console.log('callback one');
};

var callback_two = function (result_from_web_service) {
 console.log('callback two');
};

// the async_calls are library calls that i don't own or modify
var x = function () {
  console.log('x is called');
  async_call_one(callback_one); 
  async_call_two(callback_two);
};

var y = function () {
 console.log('y is called');
};

Test:
x();
y();

// prints: 'x is called', 'y is called', 'callback one', 'callback two'
// what i need: 'x is called', 'callback one', 'callback two', 'y is called'

我做的事做到这一点在呼唤Y()内call_back_two:

What I did to accomplish this was calling y() inside call_back_two:

var callback_two = function (result_from_web_service) {
   console.log('callback two');
   y();
};

但现在我的使用情况要求y中的回调外(将我的code的用户调用)被调用。即,x()和y的呼叫()是独立的方式,x的呼叫()不最终调用γ()。 Y()应独立调用,但仅当x()和它的回调处理。认为X()作为像创建Java和Y()的对象作为一种方法,只要你想,你会打电话。

But now my use case requires that y be called outside of the callback (will be called by the user of my code). i.e. the calling of x() and y() be independent in a way that the calling of x() doesn't end up calling y(). y() should be called independently but only if x() and its callbacks are processed. think of x() as like creating an object in java and y() as a method you would call whenever you want.

//.. some code, x() does some kind of initialization...
x();

// OPTIONALLY call y(), but make sure x() and its callbacks are processed
y();

我试过以下,但不起作用。

I tried the below but doesn't work.

 $.when(x()).then(y());

谢谢,

推荐答案

做这样的事情的唯一途径妥善就是让异步的。基本上,内部等待 X 执行自己的code之前完成。这是类似的东西像 domready中的onload 这等待其他的东西执行自己的逻辑前发生。

The only way to make something like this work properly is to make y asynchronous. Basically, y internally waits for x to complete before executing its own code. This is similar to things like domready or onload which waits for other things to happen before executing their own logic.

有两种方法来实现这一点。第一,最简单,最原始的方法就是的setTimeout 轮询。让 X 设置变量或属性,并检查执行前:

There are two ways to accomplish this. The first, simplest and most naive way is setTimeout polling. Make x set a variable or attribute and check that before executing:

function y () {
    if (x.ready) {
        /* do what you need to do here */
    }
    else {
        setTimeout(y,100);
    }
}

第二个方法是创建虚拟事件或承诺。并非所有的承诺库支持使用已经到期(我自己自制的人做),所以你可能需要编写自己的控制流来处理这种情况的承诺。为此,你需要重写 X 来支持一个事件或承诺般API:

The second method is to create virtual events or promises. Not all promise libraries support using a promise that has already expired (my own homemade one does) so you may need to write your own control flow to handle that case. For this you need to rewrite x to support an event or promise-like api:

var x = (function () {
    var async_calls = 2;
    var callback;

    f = function () {
        console.log('x is called');
        async_call_one(function(){
            async_calls --;
            if (async_calls == 0 && callback) callback();
            callback_one();
        }); 
        async_call_two(function(){
            async_calls --;
            if (async_calls == 0 && callback) callback();
            callback_two();
        });
    }

    f.loaded = function (loaded_callback) {
        callback = loaded_callback;
        if (async_calls == 0) callback();
    }         

    return f;
})();

现在在您可以使用 x.loaded 功能时,x是执行您的code加载:

Now in y you can use the x.loaded function to execute your code when x is loaded:

function y () {
    x.loaded(function(){
        /* do what you need to do here */
    });
}

当然,这有使异步的问题。因此,如果用户希望写类似:

Of course, this has the problem of making y asynchronous. Therefore if your users expect to write something like:

y();
a();
b();

然后 A B 可能会或可能不会在执行是。为了解决这个问题,你需要做接受回调,使您的用户可以控制他们的程序流程:

then a and b may or may not execute before y. To solve this you need to make y accept a callback so that you users can control their program flow:

function y (callback) {
    if (x.ready) {
        /* do what you need to do here */
        callback();
    }
    else {
        setTimeout(function(){y(callback)},100);
    }
}

function y (callback) {
    x.loaded(function(){
        /* do what you need to do here */
        callback();
    });
}

因此​​,他们不得不使用是这样的:

y(function(){
    a();
    b();
});

另外,您可以让返回一个承诺,如果你preFER的风格。

Alternatively you can make y return a promise if you prefer that style.

这篇关于JavaScript的:后调用另一个函数的回调函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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