Trebond
Trebond

Reputation: 57

Understanding bind in the context of Promises

So I was taking a look at this thread discussing retrying promises and I was curious as to how and why bind was used in this particular piece of code. This piece of code was used a helper function by a poster to delay and retry promises that were rejected.

var t = 500;

function rejectDelay(reason) {
    return new Promise(function(resolve, reject) {
        setTimeout(reject.bind(null, reason), t); 
    });
}

As I understand it, bind is used to redefine the scope. When you bind to null, you bind to global scope, but what is the reason for binding the rejection of a promise globally? Essentially, why does the scope of the reject portion of handling a promise matter? Thank you for your help.

Upvotes: 0

Views: 479

Answers (1)

deceze
deceze

Reputation: 522412

The bind is not used to bind context (this) here. Context is pretty irrelevant for the reject function anyway, as it's not an object method. No, bind here is used to bind the first argument, reason. You simply need to also supply a value for context first (here null). reject.bind(null, reason) returns a function that when called invokes reject with reason as its first argument. Another way to write this would be:

setTimeout(() => reject(reason), t);

Yet another way—and IMO the most elegant—would be:

setTimeout(reject, t, reason);

setTimeout accepts further arguments which it will pass through to the callback.

Upvotes: 3

Related Questions