2017-10-19 148 views
0
  1. 我有一個用戶填寫一些文本框的sharepoint表單。如何正確使用promise?

  2. 用戶點擊保存按鈕。腳本從這裏運行。

  3. 檢查是否所有的texbox被填滿。

  4. 如果不錯,根據輸入從外部列表中獲取一些字段並基於該列表更新其他列表。

  5. 將輸入保存爲新項目。

問題:我使用了一個名爲PreSaveAction()功能。這在用戶點擊「保存」按鈕時調用,並且只有在該表單返回true時才被保存。所以在返回true之前,我應該做現場檢查和列表更新,我不知道在哪裏添加這個return true。如果我直接在PreSaveAction()之內添加它,它會運行異步,因此在更新完成之前有30-40%的機會返回。我是JavaScript新手,所以我需要一點幫助。

我的簡化代碼如下所示:

function PreSaveAction() //This start if the user click on the save button, and create a new item if return with true 
{ 
    var promresult; 
    if(textbox!="") 
    { 
    //do my staff based on promise like: promresult=promise.then(input textbox, get list field).then(update).then(resolve true, fail false) 
    return promresult; //this run before the update is completed and promresult get value 
    } 
    else 
    { 
    return false; //nothing happens if the textboxes are not filled yet. 
    } 

} 

我讀到promises,我想我通情達理的,他們是如何工作的,但在我的情況下,PreSaveAction()具有多種功能(檢測的onclick,做我的東西,而歸真假)。我嘗試了幾種方法,但是我沒有找到解決方案在哪裏以及如何將預計回報等待我的承諾完成?還是應該使用完全不同的方法?非常感謝您的親切幫助!

+0

如果沒有在函數中看到實際的異步代碼,人們將無法幫助您。看起來你正試圖從一個函數中返回一個異步檢索的值。你不能這樣做。該值在函數返回時不可用。異步回調將在稍後調用。 – jfriend00

+0

我簡化了代碼,並嘗試將重點放在problam上,因爲我不想用長且難以理解的代碼來惹惱ppl。但看起來你有我的問題的想法。那麼這是不可能的?你會用什麼其他類型的解決方案來歸檔類似的東西?我的問題是這個「Presaveaction」是一個集成函數,我不知道如何將它分解成組件。例如:如果我將使用簡單的onlcick事件,請在下一個函數中執行檢查,更新列表,並強制保存在3.函數中,它會起作用嗎? – Nefri

+0

Stackoverflow不適用於理論問題。它在實際代碼和一個非常具體的問題上運行得更好。你的問題的執行部分都在你的異步代碼中,你沒有分享過,所以你的問題幾乎完全是理論上的。鑑於此,我可以提供的最佳答案是[如何從異步調用返回響應](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from -an異步呼叫/ 14220323#14220323)。 – jfriend00

回答

0
function PreSaveAction() //This start if the user click on the save button, and create a new item if return with true 
{ 
    var promresult; 
    if(textbox!="") 
    { 
    //do my staff based on promise like: promresult=promise.then(input textbox, get list field).then(update).then(resolve true, fail false) 
    return promresult; //this run before the update is completed and promresult get value 
    } 
    else 
    { 
    return Promise.resolve(false); //nothing happens if the textboxes are not filled yet. 
    } 

} 

PreSaveAction() 
    .then(function(result){ 
    if (result===false) { 
     // this means the textboxes are not filled yet 
    } else { 
     // result is whatever is returned from promresult 
    } 
    }) 
+0

嗨!我測試了它,看起來像Presaveaction()。然後()結構不起作用。你確定這是否符合這樣的承諾?或者,也許我是一個做錯了,但我得到,「SyntaxError:意外的令牌。」從這一行:( – Nefri

+0

也許'promresult'不是承諾,你沒有發佈你的實際的promresult代碼,所以我真的不知道它是什麼,Anythign可能是錯誤的 – TKoL