链接多个异步函数

时间:2012-07-12 11:02:59

标签: javascript firefox-addon firefox-addon-sdk promise

简介

我有一个问题来自这个:

Loop calling an asynchronous function

一旦我得到一个循环,它使用类似promises的模式调用异步函数(使用SDK开发的附加组件中的jsdeferred库)。

var sess = ...;
Deferred.define(this);      
function asyncFunction (session) {
    Deferred.next(function() {
        var d = new Deferred();
        (new Request({
              url: form.php,
              content: "sess=" + session,
              onComplete: function (response) {
                  d.call(response.json);
              }
        })).get();
        return d;
    }).next(function(resp) {
        if (resp.id) {
            asyncFunction(session);
            console.log(resp.msg);              
        }           
    });
}

asyncFunction(sess);

我想将一个新的异步函数链接到这个请求中,例如,打开浏览器的选项卡:我不希望继续执行直到准备好。

问题

所以我明白了:

var sess = ...;
Deferred.define(this);      
function asyncFunction (session) {
    Deferred.next(function() {
        var d = new Deferred();
        (new Request({
              url: form.php,
              content: "sess=" + session,
              onComplete: function (response) {
                  d.call(response.json);
              }
        })).get();
        return d;
    })
    .next(function(resp) {
        var d = new Deferred();
        // Load tab
        tabs.activeTab.url = 'http://foo.com';
        tabs.activeTab.on('ready', function() {
            console.log(resp.id);
            d.call(resp.id); 
        });
        return d;
    })
    .next(function(resp) {
        if (resp.id) {
            asyncFunction(session);
            console.log(resp.msg);              
        }           
    });
}

asyncFunction(sess);

我得到的结果是,对于循环的每次迭代,它再次运行所有先前的请求!所以我在我的控制台中得到了以下日志:

id1
msg1
id1
msg1
id2
msg2
id1
msg1
id2
msg2
id3
msg3
...

显然我的期望是:

id1
msg1
id2
msg2
id3
msg3

问题

很明显,我不理解承诺模式。我在两个API中看了很多:

第一个是我一直在使用的那个。当我尝试要求库时,第二个出错:

const { defer } = require('api-utils/promise'); (+)

所以,我的问题是,如果你知道任何好的承诺教程或一些关于链接多个异步函数的好例子。或者如果你知道怎么做,你会怎么做。

谢谢

编辑:给出行(+)

的错误
error: An exception occurred.
Traceback (most recent call last):
  File "resource://ares-at-iiia-dot-csic/api-utils/lib/promise.js", line 16, in 
    }.call(this, function(require, exports) {
  File "resource://ares-at-iiia-dot-csic/api-utils/lib/promise.js", line 6, in return     function promised
    if (typeof(define) === 'function') { // RequireJS
  File "function promisedConcat(promises, unknown) {return promises.then(function         (values) {return resolve(unknown).then(function (valu
e) {return values.concat(value);});});", line NaN, in function promisedConcat
  File "function execute(args) {return call.apply(call, args);", line NaN, in function     execute
  File "exports.reject = reject;var promised = function () {var call =     Function.call;var concat = Array.prototype.concat", line NaN, in
 exports.reject = reject;var promised = function 
  File "function reject(reason, prototype) {var deferred =         defer(prototype);deferred.reject(reason);return deferred.promise;", line NaN
, in function reject
  File "exports.resolve = resolve", line NaN, in exports.resolve = resolve
  File "function resolve(value, prototype) {var deferred =     defer(prototype);deferred.resolve(value);return deferred.promise;", line NaN
, in function resolve
  File "exports.defer = defer", line NaN, in exports.defer = defer
  File "if (pending) {pending.push([resolved, rejected]);} else {result.then(resolved,     rejected);}return deferred.promise;}}});var defe
rred = {promise: promise, resolve: function resolve(value) {if (pending) {result =     isPromise(value) ? value : resolution(value);while (
pending.length) {result.then.apply(result, pending.shift());}pending = null;}},     reject", line NaN, in if 
  File "function rejected(reason) {deferred.resolve(reject(reason));", line NaN, in     function rejected
  File "function resolved(value) {deferred.resolve(resolve(value));", line NaN, in     function resolved
  File "function defer(prototype) {var pending = [], result;prototype = prototype ||     prototype === null ? prototype : Object.prototype;
var promise = Object.create(prototype, {then: {value: function then(resolve, reject)     {var deferred = defer(prototype);resolve = resolve
 ? attempt(resolve) : resolution;reject = reject ? attempt(reject) ", line NaN, in     function defer
  File "function isPromise(value) {return value && typeof value.then === "function";",     line NaN, in function isPromise
  File "function attempt(f) {return function effort(options) {try {return f(options);}     catch (error) {return rejection(error);}};", lin
e NaN, in function attempt
  File "function rejection(reason) {return {then", line NaN, in function rejection
  File "function resolution(value) {return {then", line NaN, in function resolution
  File "((function (require, exports) {"use strict"", line NaN, in 
  File "resource://ares-at-iiia-dot-csic/api-utils/lib/globals!.js", line 75, in getter
    value: define.bind(this)
TypeError: can't redefine non-configurable property 'define'

1 个答案:

答案 0 :(得分:2)

嗯,看起来有点像范围问题。在你的上一个函数中,应该没有变量resp可用 - 我不确定它真正记录的是什么。

是的,因为你最后再次调用asyncFunction,只要响应中有一个id,你就可能得到一个无限循环。

但是,让我们尝试使用add-on sdk's promises(不,之前我从未使用过它们 - 但它说它基于CommonJS Promises/A):

const { defer } = require('api-utils/promise');
// or whatever you need in your code to use them - I'm no addOn-developer

var sess = ...;
Deferred.define(this);      
function asyncFunction (session) {
/* returns a promise itself */

    var d = defer();
    (new Request({
        url: form.php,
        content: "sess=" + session,
        onComplete: function (response) {
            d.resolve(response.json);
        }
    })).get();
    return d.promise.then(function(resp) {
        var d = defer();
        // Load tab
        tabs.activeTab.url = 'http://foo.com';
        tabs.activeTab.on('ready', function() {
            d.resolve(resp);
        });
        return d.promise;
    }).then(function(resp) {
        console.log("request #"+resp.id+"sucessful: "+resp.msg);  
        if (resp.id) {
            asyncFunction(session); // call recursively
        }           
    });
}
asyncFunction(sess);