質問

I am having trouble with creating / understanding promises. I understand the advantages and understand how to use them. Creating own promise-functionality is the difficult part. Simply, how do I convert this function to work with promises:

ret.getDataByGame = function (gameID, playerID) {
     var cb = new callbackHelper();

      models.gameData.find( {  }, function (err, found) {
          if (err) {
              console.log("error in getting gamedata for gameID: "+gameID);
              cb.setData(void 0);
          } else {
              cb.setData(found);
          }
      });
    return cb;
};
function callbackHelper() {
    var self = this;
    this.data = false;

    this.setData = function (data) {
    self.data = data;
};

It should not matter what framework or vanilla js you use to show the example to me.

役に立ちましたか?

解決

ret.getGameDataByGame = lib.promisify(models.gameData.find);

might suffice. Or use a dedicated node-style callback helper function:

ret.getGameDataByGame = function(gameID, playerID) {
    return lib.ninvoke(models.gameData, "find", {…});
};

For the Q library, check the Adapting Node section of its docs.


For creating a promise with the pattern you've used for your callbackHelper thing, your promise library typically offers Deferreds. You would use them like this:

ret.getDataByGame = function (gameID, playerID) {
    var def = new lib.Deferred();
    models.gameData.find({…}, function (err, found) {
        if (err) {
            def.reject("error in getting gamedata for gameID: "+gameID);
        } else {
            def.fulfill(found);
        }
    });
    return def.promise;
};

See also the The Beginning section in the Q docs.

他のヒント

Just to give a second input, I quickly looked at the promise implementation of Q docs, but this is the implementation that I use, which is supported by default, in browsers (except IE). With respect to your posted algorithm:

//define promise structure for callback function of interest
ret.getDataByGame = function(gameID, playerID){

  return new Promise(function(resolve,reject)
  {
    try
    {
        //do any callback function etc. which you want to do
        models.gameData.find({},function(err, found){
            if(err)
            {
                console.log("error in getting gamedata for gameID: "+gameID);
                reject(err); //if there is error, save as reject
            }
            else
                resolve(found); //if have solution, save as resolve
        }
    }
    catch(exc)
        {reject('Error exc gameData.find: '+exc.message);}

  });   //end of Promise
}

And then where you call your class functions etc.:

//where you physically call the function you defined as a promise function
ret.getDataByGame('input1','input2').then(function(output){

    alert("woohoo, you are awesome!, output = "+output);

},function(error){

    alert("Output error:\r\n"+error);

});

Here is the definition and implementation of promises which I consider as the "standard" thus far, with browser support versions: Promise doc + tutorial. An the cool thing if you do it for massive amounts of data, and they are async, you really optimize your execution time!! such as:

//repeat promise function
function repeatPromise(inputDataArray)
{
  for(var i = 0; i < inputDataArray.length; i++)
  {
    //where you physically call the function you defined as a promise function
    ret.getDataByGame(inputDataArray[i].input1,inputDataArray[i].input2).then(function(resolve){

        alert("Output is in async, output = "+resolve);

    },function(error){      
        alert("Output error:\r\n"+error);   
    });
  } //end of for loop
} //end of function

Hope this helps :)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top