Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

How do I sequentially chain promises with angularjs $q?

In the promise library Q, you can do the following to sequentially chain promises:

var items = ['one', 'two', 'three'];
var chain = Q();
items.forEach(function (el) {
  chain = chain.then(foo(el));
});
return chain;

however, the following doesn't work with $q:

var items = ['one', 'two', 'three'];
var chain = $q();
items.forEach(function (el) {
  chain = chain.then(foo(el));
});
return chain;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Redgeoff, your own answer is the way I used to translate an array into a chained series of promises.

The emergent de facto pattern is as follows :

function doAsyncSeries(arr) {
    return arr.reduce(function (promise, item) {
      return promise.then(function(result) {
        return doSomethingAsync(result, item);
      });
    }, $q.when(initialValue));
}

//then
var items = ['x', 'y', 'z'];
doAsyncSeries(items).then(...);

Notes:

  • .reduce is raw javascript, not part of a library.
  • result is the previous async result/data and is included for completeness. The initial result is initialValue. If it's not necessary to pass `result, then simply leave it out.
  • adapt $q.when(initialValue) depending on which promise lib you use.
  • in your case, doSomethingAsync is foo (or what foo() returns?) - in any case, a function.

If you are like me, then the pattern will look, at first sight, like an impenetrable cludge but once your eye becomes attuned, you will start to regard it as an old friend.

Edit

Here's a demo, designed to demonstrate that the pattern recommended above does in fact execute its doSomethingAsync() calls sequentially, not immediately while building the chain as suggested in the comments below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...