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

Know if operation succeeded or rejected with promises

本文关键字:承诺 拒绝 成功 操作      更新时间:2023-09-26

我有一个主函数,我想在其中检查记录是否存在,以便创建或更新记录,所以在这个函数中,我调用一个助手函数,该函数使用ajax调用来检查该记录,然后我希望将true/false返回到主函数,但我是否返回defrred.resolve()和deferred.rejectt(),以及如何检查它们?我似乎无法兑现承诺。

下面是我的代码,任何提示都将不胜感激。

   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?
    }
}

您需要从_isRecordExists函数返回promise对象。然后在_helperFunction中,如果块将被转换为上一次检查返回的承诺的成功/错误回调:

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

这里还有一个重写的_helperFunction,它使用真正的promise(使用polyfill或native)实现:

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

function _mainFunction()(处出现语法错误,在)处关闭_mainFunction();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()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

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

然后我想要一个真/假返回到主函数

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

您可以做的是在_mainFunction中返回Promise,然后使用.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进行异步编程。

以下是您可能想阅读的有用链接:

  • 异步JavaScript编程
  • jQuery Deferred/Promise及其总体设计模式介绍