2015-12-20 81 views
2

我有一個主要功能,我想檢查一個記錄是否存在或不是爲了創建或更新記錄,所以在這個函數中我調用了一個幫助函數來檢查記錄使用ajax調用,然後我想要一個真/假返回到主函數,但是我返回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? 
 
    } 
 
}

回答

1

你需要從_isRecordExists函數返回的承諾目標。

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:那麼在_helperFunction如果塊wouldbe轉化爲成功/許的錯誤回調從以前的檢查返回

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

返回你應該從'_helperFunction'返回承諾爲好,或4號線將拋出一個錯誤。 – DCoder

+0

@DCoder真的,謝謝! – dfsq

+0

所以如果記錄不存在,這意味着查詢失敗,並進入失敗回調,所以我可以調用創建函數?調用函數來創建失敗的東西是否是一個好習慣?對不起,我還是這個新手。 – user5699896

-1

那麼我想真/假返回到主函數

你ç不要將true/false返回給主函數,因爲當代碼執行完成時,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的異步編程工作。

這些是您可能需要閱讀的有用的鏈接:

+0

感謝您的回答。你能告訴我你在代碼中看到了什麼,我可以改進嗎? – user5699896

+0

'_isRecordExists'函數和'決定'表明你仍然在思考同步編程,或者「程序設計」(如C或Pascal)。您應該閱讀我在答案中提到的文章,以瞭解如何正確編寫代碼並熟悉JavaScript中的異步。祝你好運。 – TrungDQ

+0

誰投下我的答案誰可以請告訴我爲什麼? – TrungDQ

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

我不是一個jquery的人,延遲創建時可能會出現語法錯誤,但是,將它想象爲一個僞代碼只是爲了給出想法 – erdysson

0

語法錯誤在function _mainFunction()(,收盤_mainFunction()); jQuery的承諾對象不是從_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>

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