A series of Promise

Promise 系列讲

Posted by starwavelin on November 12, 2018

In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete. – excerpt from Wikipedia

When client side needs data that resolved from server side first

async clientFtn(): Promise<void> {
  await serverFtn();
  // Use data resolved from server side function
}

Promise Loop

X = A & B & C   // A, B, C, who gets executed first does Not matter

promise.all([A,B,C]);
X = A -> B -> C   // A, B, C, who gets executed in order

[A,B,C].reduce((result, i) => result.then(i), Promise.resolve());

But, if doing so causes some trouble, ie. The pool is probably full issue, you can use a conservative for of loop way.

for (const el of this.array) {
  this.map[el] = await this.fetchMap(el);
}

Sometimes we don’t use array.map() is because array.map() is asynchronous and we need execution in sequence, as we want in this for ... of ... loop.

When for of is not the solution

We can transform the code snippet above into

await Promise.all(this.array.map(async el => {
  this.map[el] = await this.fetchMap(el);
}));

async/await way of handling JS Loop

Article showing good examples:

  1. Process Array in Sequence
  2. Process Array in Parallel may also work.

Old Way

addFetchDataTokenServer() {
  return this.refreshStudentData()
    .then(function updateStudentToken() {
        return this.selectedStudent.addFetchDataToken();
    }.bind(this));
}

New Way

async addFetchDataTokenServer() {
  await this.refreshStudentData();
  return this.selectedStudent.addFetchDataToken();
}

Much more simplified.

Promise.something vs. Bluebird.something

Promise.all is a better standard, it’s default javascript, and if we use async await anyway, it will default wrap the result of this method’s execution in a bluebird promise
But since we have Bluebird.all available, we can use it directly without relying on the default wrapping.

Bluebird is a super set of native Promise so it is able to consume promise; that’s why wrapping to Bluebird can happen.

What is Bluebird?

Further Reading