知道操作是否成功或被承诺拒绝

时间:2015-12-20 07:47:14

标签: javascript jquery promise

我有一个main函数,我想检查一条记录是否存在,以便创建或更新记录,所以在这个函数中我调用一个帮助函数,用ajax调用检查该记录,然后我想要将true / false返回给main函数,但是我是否返回defrred.resolve()和deferred.reject(),我该如何检查它们?我似乎无法在承诺中实现它。

以下是我的代码,任何提示都表示赞赏。



   function _mainFunction()(
        var recordID = prompt("Enter Desired Record ID");
        var promise =  _helperFunction(recordID);
        promise.then(...) //do some processing when the reocrd is created or updated
)
        
        
   function _helperFunction(passedId){
   if (passedId) {
            if (!_isRecordExists(passedId)) {
              // if record doesn't exist, create it.
            }
        }
   }



    function _isRecordExists(passedId){
        var decision;
        var baseUrl = "some url";
        var dfd = $.ajax({
            url: baseUrl,
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "accept": "application/json;odata=verbose"
            }
        });
        dfd.promise().then(
            function(data, status, jqXHR){
                decision = true;
                dfd.resolve();
            }, 
            function (jqXHR, status, error) {
                decision = false;
                dfd.reject();
            });

        return decision; // do I return decision here for true or false?
    }
}




5 个答案:

答案 0 :(得分:1)

您需要从_isRecordExists函数返回promise对象。然后在_helperFunction if-block将转换为从上一次检查返回的promise的成功/错误回调:

function _mainFunction() {
    var recordID = prompt("Enter Desired Record ID");
    var promise = _helperFunction(recordID); 
    promise.then(function() {
        console.log('Do something else');
    }, function() {
        console.log('Failed to find and create new. Maybe try again');
    });
}

function _helperFunction(passedId) {
    return $.Deferred(function(deferred) {
        if (passedId) {
            _isRecordExists(passedId).then(function(recordObj) {
                // record exists, do something with it
                console.log('Exists');
                deferred.resolve(recordObj);
            }, function() {
                // record doesn't exist, create it.
                console.log('Does not exist');
                deferred.reject();
            });
        }
        deferred.reject();
    }).promise();
}

function _isRecordExists(passedId) {
    var decision;
    var baseUrl = "some url";
    return $.ajax({
        url: baseUrl,
        type: "GET",
        contentType: "application/json;odata=verbose",
        headers: {
            "accept": "application/json;odata=verbose"
        }
    });
}

这里也是一个用真正的承诺(用polyfill或native)实现的重写_helperFunction

function _helperFunction(passedId) {
    if (passedId) {
        return Promise.resolve(_isRecordExists(passedId)).then(function(recordObj) {
            // record exists, do something with it and pass further
            return recordObj;
        }, function() {
            // record doesn't exist, create it
            return createNewRecord(); // createNewRecord should return new promise
        });
    }
    return Promise.reject();
}

答案 1 :(得分:0)

    function _mainFunction(){
        var recordID = prompt("Enter Desired Record ID");
        _helperFunction(recordID)
            .then(function(decision) {
                // you can use decision here
            })
            .catch(function(decision) {
                // passing decision as true or false in _isRecordExists fn, just for information
                // or future usages
                // then / catch status already gives the idea
            });
    }

   function _helperFunction(passedId){
        var deferred = $.deferred();
        if (passedId) {
            _isRecordExists(passedId))
                .then(function(data) { 
                    // then means exists : do whatever you want here
                    // if you want to return the result as promise;
                    deferred.resolve(data);
                })
                 .catch(function(errorData) {
                    // catch means does not exist : create or do anything
                    deferred.reject(errorData);
                 });
        } else {
            // no id provided
            deferred.reject();

        }
        return deferred.promise();
   }

   function _isRecordExists(passedId){
        var decision;
        var baseUrl = "some url";
        var dfd = $.ajax({
            url: baseUrl,
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "accept": "application/json;odata=verbose"
            }
        });
        return dfd.promise().then(
            function(data, status, jqXHR){
                decision = true;
                dfd.resolve(decision);
            }, 
            function (jqXHR, status, error) {
                decision = false;
                dfd.reject(decision);
            });
    }
}

答案 2 :(得分:0)

function _mainFunction()(处的语法错误,_mainFunction()的{​​{1}}附近; jQuery promise对象未从)返回



_helperFunction

function _mainFunction() {
  var recordID = prompt("Enter Desired Record ID");
  var promise = _helperFunction(recordID);
  promise.then(function success(t) {
      // resolved 
      console.log(t)
    }, function err(e) {
      // rejected
      console.log(e)
    })
    //do some processing when the reocrd is created or updated
}

function _helperFunction(passedId) {
  if (passedId) {
   // return `_isRecordsExists`
   return _isRecordExists(passedId)
      .then(function(data) {
        return data
      }, function err(data) {
        return data
      })
  } else {
    // if `passedId` not entered, return rejected deferred 
    return $.Deferred().reject("no passedID")
  }
}

function _isRecordExists(passedId) {
  var decision;
  var baseUrl = "some url";
  // do asynchronous stuff
  // var dfd = $.ajax({
  //      url: baseUrl,
  //      type: "GET",
  //      contentType: "application/json;odata=verbose",
  //      headers: {
  //          "accept": "application/json;odata=verbose"
  //      }
  //    });
  var dfd = $.Deferred(function(d) {
    setTimeout(function() {
      d.resolve()
    }, Math.random() * 2000)
  });
  // return `dfd` promise here
  return dfd.promise().then(
      function(data, status, jqXHR) {
        decision = true;
        return decision
      },
      function(jqXHR, status, error) {
        decision = false;
        return decision
      })
    // return dfd.promise(); 
    // do I return decision here for true or false?
}

_mainFunction()




答案 3 :(得分:0)

   function _mainFunction() {
        var recordID = prompt("Enter Desired Record ID");
        var promise =  _helperFunction(recordID);
        promise.then(...) //do some processing when the reocrd is created or updated
}
        
        
   function _helperFunction(passedId){
   if (passedId) {
            if (!_isRecordExists(passedId)) {
              // if record doesn't exist, create it.
            }
        }
   }



    function _isRecordExists(passedId){
        var decision;
        var baseUrl = "some url";
        var dfd = $.ajax({
            url: baseUrl,
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "accept": "application/json;odata=verbose"
            }
        });
        dfd.promise().then(
            function(data, status, jqXHR){
                decision = true;
                dfd.resolve();
            }, 
            function (jqXHR, status, error) {
                decision = false;
                dfd.reject();
            });

        return decision; 
        // do I return decision here for true or false?
        // answer: NO!!, before the value(true or false) is assigned to decision, decision is returned...(Of course, the value may be allocated and then return). The Promise object should return to the place where the actual value is used.
    }
}


   // here is my answer
   function _mainFunction(passedId){
       var recordID = prompt("Enter Desired Record ID");
       isExistPromise = _isRecordExists(recordID);
       isExistPromise.then(function(data){
           if (data.isExist) {}
           else {}
       });
   }

    function _isRecordExists(passedId){
        var decision;
        var baseUrl = "some url" + passedId;
        return $.ajax({
            url: baseUrl,
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "accept": "application/json;odata=verbose"
            }
        });
     }

答案 4 :(得分:-1)

  

然后我希望将true / false返回到主函数

你不能将true / false返回给main函数,因为当你的代码完成执行时,promise仍然有效并且还没有结果,因此你的_mainFunction不知道它是否应该返回true或false。

您可以做的是在_mainFunction中返回一个承诺,然后使用.then.fail来执行您的逻辑代码。

function _mainFunction()(
    var recordID = prompt("Enter Desired Record ID");
    var promise =  _helperFunction(recordID);
    promise.then(function (result) {
       if (result == true) {
          // Do something
       } else {
          // Do something else
       }
    })
)

function _helperFunction() {
    return $.ajax(...)
            .then(function (response) {
                if (...) {
                    return true;
                } else {
                    return false;
                }
            });
}

从我在代码中观察到的情况来看,我认为您应该花一些时间学习如何使用JavaScript进行异步编程。

这些是您可能想要阅读的有用链接: