Lostfields Lostfields - 18 days ago 5
Node.js Question

How to not run a Promise before I ask to

I thought I had it all figured out regarding Promise, but this one actually throws me out of bed. When creating a new Promise with a executor taking two arguments, why is this method running before I either take then() or catch() at that promise

Running node 6.2.2.

import assert = require('assert');

describe("When working with promises", () => {
let ar = [1, 2, 3, 4, 5, 6];

beforeEach(() => {

})

it("should be perfectly fine but isn't when mapping to promises", (done) => {
ar.map(num => {
return new Promise((resolve, reject) => {
done(new Error('Why on earth is ' + num + ' called'));
})
})

done();
})

it("should be perfectly fine when mapping to methods", (done) => {

ar.map(num => {
return (resolve, reject) => {
done(new Error(num + ' is not called ever'));
}
})

done();
})
});


First test fails, and second test is successful.

Answer

If you check the documentation for Promise, you will find that the function that is given to the constructor is run immediately. It is supposed to kick off the asynchronous calculation and install the two callbacks there (so that resolve and reject are not invoked just now, but whenever that calculation completes or fails).

The Promise function is not the asynchronous calculation, it just wraps that calculation and the two callbacks you need to keep track of it together into a nice package.

Your second example creates an anonymous function for each number, but does not invoke any of them.

why is this method running before I either take then() or catch() at that promise

The Promise does not care if you install any handlers/chains. The calculation will have been started (or not) no matter if anyone is watching it or not.

Comments