在JavaScript中链接多个异步方法

在JavaScript中链接多个异步方法

本文介绍了在JavaScript中链接多个异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个JavaScript库,以将ajax请求抽象到我的HTTP API.我的每个JavaScript函数都是jquery的ajax调用的包装,该调用在完成时向用户进行回调.

I am writing a javascript library to abstract ajax requests to my HTTP API.Each of my javascript functions is a wrapper for jquery's ajax call, which makes a callback to the user on completion.

例如.

mylib.doThing( "foo", { success:function(){alert("done");});

在我要连续两次执行mylib.doFoo的情况下,我会遇到类似的事情:

In the case where I want to execute mylib.doFoo twice in series, I have something like:

mylib.doThing( "foo", { success:function(){ mylib.doThing( "bar", { success:function(){alert("done");}); });

对于仅需两个步骤的操作,很快就会变得混乱.

For anything more that two steps, this gets messy very quickly.

是否可以提供更简洁的语法,也许更像以下内容?以及我该如何实现mylib.doThing()?

Is it possible to provide a cleaner syntax, perhaps more like the following? And how would I need to implement mylib.doThing()?

mylib.doThing("foo").mylib.doThing("bar").alert("done");

推荐答案

function doThingFluent(a, b) {
  return {
    _name : a,
    _chainedCall : b,
    doMoreThingFluent : function(a1) {
      return doThing(a1, this);
    },
    done : function(callback) {
      var chained = this._chainedCall;
      var name = this._name;
      while (chained) {
        callback = function(n, c) {
          return function() {
            mylib.doThing(n, { success : c });
          };
        } (name, callback);
        name = chained._name;
        chained = chained._chainedCall;
      }

      mylib.doThing(name, {success: callback});
    }
 };

 doThingFluent("foo").doMoreThingFluent("bar").done(function(){alert("done");})

这篇关于在JavaScript中链接多个异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 02:18