如何将Promise的值传递给另一个函数?

时间:2016-07-20 21:39:04

标签: javascript node.js asynchronous promise q

我对Javascript有点新手,并且很难处理它的异步方面。我的程序检查两个对象的值,其中第二个对象没有我需要的重要属性来完成检查。所以我承诺获得该值/属性(ID),现在我需要将该ID值传递给检查函数。 check函数应该只返回一个true / false来查看ID是否匹配。 check函数的值被传递给另一个函数,然后该函数适当地执行并在必要时编辑该事物。所以我基本上无法访问它的括号内的tick值。我已经将代码片段包含在所有这些内容中,因为所有这些都更容易用它进行可视化。有人能为我提供这个问题的解决方案吗?任何建议都会有很大的帮助!我希望尽可能减少对脚本的修改。

    var Q = require('q');

    getID = function(instance, person, callback){
          var = deferred = Q.defer();
          var url = 'www.blah.com'; 
          var options = {
              'url': url
          };

          request.get(options, function(error, response, body){
              if (error) {
                  deferred.reject(error);
              }else{
                  var res = body;
                  var obj = JSON.parse(res);
                  var id = obj.id;
                  deferred.resolve(id);
              } else deferred(obj);
          });


    check = function(instance, thing1, thing2){ 
        var tick = true;
        getID(instance, thing2).then(function(id)){
            var id_1 = thing1.id; // thing1 passed into check with ID
            var id_2 = thing2.id; // thing 2 now has id attached to it
            if( id_1 == id_2 ){
                tick = true; // VALUE 1 
            }else{
                tick = false; // VALUE 2
        });

        // NEED VALUE 1 OR 2 OF TICK HERE 

        if(thing1.name == thing2.name){
            tick = true;
        else{
            tick = false;
        }

        // similar checks to name but with ADDRESS, EMAIL, PHONE NUMBER
        // these properties are already appended to thing1 and thing 2 so no need to call for them

    };

    editThing = function(instance, thing, callback){

        var checked = check(instance, thing1, thing2);
        if(checked){
            // edit thing
        }else{
            // don't edit thing          
    };

2 个答案:

答案 0 :(得分:1)

由于您承诺要完成工作,并且您需要从该工作中获得输出,因此您需要将该承诺传递给想要最终输出的代码。< / p>

我不会尝试重写你帖子中的代码,所以请允许我解释一下:

getThing = function(thing){
  var deferred = Q.defer();
  ...
  request.get(options, function(error, response, body){
    if (error) {
      deferred.reject(error);
    } else {
      ...
      deferred.resolve(thingMadeFromResponse);
    }
  });
  return deferred;
}

check = function(thingWeHave, thingWeNeedFetched){ 
  return getThing(thingWeNeedFetched).then(function(thingWeFetched)){
    // check logic
    checked = thingWeHave.id == thingWeFetched.id;
    ...
    return checked;
  });
};

editThing = function(instance, thing, callback){
  check(thingWeHave, thingWeNeedFetched).then(function(checked) {
    if(checked){
        // edit thing
    }else{
        // don't edit thing
    }
  });
};

答案 1 :(得分:-2)

Promises

“thenable”是定义then方法的对象或函数。

C