简体   繁体   English

创造承诺

[英]Creating promises

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: 简单地说,如何将此函数转换为使用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. 你使用什么框架或vanilla来向我展示这个例子并不重要。

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. 对于Q库,请检查其文档的“ 调整节点”部分


For creating a promise with the pattern you've used for your callbackHelper thing, your promise library typically offers Deferreds . 要使用您用于callbackHelper的模式创建承诺,您的承诺库通常会提供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. 另请参阅Q文档中的“开始”部分

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). 为了给出第二个输入,我快速查看了Q docs的promise实现,但这是我在浏览器(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 . 以下是我认为是“标准”的promises的定义和实现,浏览器支持版本: 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM