1

I'm currently trying to create a tool to chain a dynamic amount of promises. Here is my code:

// NB: This is made using angular's $q, but this applies to anything else
promiseChain = function(array, passedPromise) {
    let chain = $q((resolve, reject) => resolve());
    for (let elem of array)
      chain = chain.then(_ => passedPromise(elem));
    return chain;
};

and here is my testing code:

// This returns a timeout wrapped in a promise
let testFn = function(s) {
  return $timeout(function() {
    console.log(s);
  }, 500);
};

let promise = makePromiseChain([1,2,3,4,5,6,7,8,9], testFn);
promise.then(_ => console.log('finished'));

This works. However, what irks me is the first line of promiseChain:

$q((resolve, reject) => resolve())

Isn't there any other way to create an empty, self resolving promise, or to start the chain? I feel dirty using this code. :/

mido
  • 24,198
  • 15
  • 92
  • 117
Apzx
  • 367
  • 1
  • 3
  • 12

1 Answers1

1

you can simply use $q.when or $q.resolve:

chain = $q.resolve(); // or the alias $q.when()

A ES6 promise resolve is Promise.resolve(), so using resolve instead of when might be easy on the next person looking at the code.

mido
  • 24,198
  • 15
  • 92
  • 117