Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Unbinds and its solution


When you are working with methods, instead of simple functions, it's highly likely that you can easily run into the common problems where passing a method to another function—such as Q.nfcall—unbinds the method from its owner. Q has to offer its services here too so that you can avoid this, by adopting any of these two ways:

  • Use Function.prototype.bind()

  • Use these methods provided by Q:

    return Q.ninvoke(redisClient, "get", "user:1:id"); // node invoke
    return Q.npost(redisClient, "get", ["user:1:id"]); // node post

There is yet another way you can create reusable wrappers, using:

  • Q.denodeify:

    //using Q.denodeify
    var readFile = Q.denodeify(FS.readFile);
    return readFile("foo.txt", "utf-8");
  • Q.nbind:

    // Q.nbind
    var redisClientGet = Q.nbind(redisClient.get, redisClient);
    return redisClientGet("user:1:id");