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

How can I pass the value of a Promise to another Function?

我对 Javascript 有点陌生,我很难理解它的异步方面。我的程序检查两个对象的值,其中第二个对象没有完成检查所需的重要 属性。所以我承诺要获得 value/property(ID),现在我需要将该 ID 值传递给检查函数。检查函数应该简单地 return a 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          
    };

Promises

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

p.then(function(value) {
   // fulfillment
   console.log(value + ' is now available and passable via function argument');
  }, function(reason) {
  // rejection
});

由于您承诺要完成工作,并且需要该工作的输出,因此您需要将该承诺传递给需要最终输出的代码。

我不会尝试重写您 post 的代码,所以请允许我解释一下:

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
    }
  });
};