簡體   English   中英

Javascript有望深入堆棧

[英]Javascript promises deep in the stack

我決定在創建模型時對服務器進行后備調用,以防萬一我們無法從本地可用信息中找到值。 我想盡可能使它異步,這是否意味着我必須使這段代碼鏈中的所有內容都消耗掉並返回承諾?

最初,我將使用偽代碼來說明這一點,因為調用棧可能會很長,因此我們不包含不是該問題中心的內容。 讓我知道您是否還需要繼續。

function router() {
    if (condition) {
        controller.renderDocument(options);
    }
}

controller.renderDocument(options) {
    documentCollection.findOrCreateDocumentHolder(options);
}

documentCollection.findOrCreateDocumentHolder(options) {
    var model = this.findOrCreateDocument(options);
}

documentCollection.otherFunction(options) {
    // just to illustrate that there's several entry points to this kind of functionality
    var model = this.findOrCreateDocument(options);
}

documentCollection.findOrCreateDocument(options) {
    if (!options.type)
        options.type = resolveType(options);
    // other things that use the found options.type
    return model;
}

resolveType(options) {
    var locallyResolved = resolveLocally(options);
    if (locallyResolved)
        return locallyResolved;
    // try the server as a fallback
    var serverResolved = resolveFromServer(options.id);
    return serverResolved;
}

resolveLocally(options) {
    return stuff;
}

resolveFromServer(id) {
    return ajaxRequestResult();
}

顯然,實際代碼要長一些,並且確實可以完成工作。

為了在管道中可能有1個ajax請求而做出所有這些使用鏈接的承諾,這感覺太過分了,尤其是因為這種情況很少見。 另一種選擇是僅發出同步AJAX請求。

我唯一的選擇是使所有內容都使用promises和whens,或使其成為同步AJAX請求嗎? 有更好的選擇嗎? 我在考慮C#的await關鍵字,但是我確定其他語言也具有類似的功能。

一旦從諾言開始,它們確實散布開來,實際上就沒有辦法解決,因為一旦異步,您就必須等待(不可行)或傳遞回調(諾言解決)。

我的方法是擁抱它們,您將更經常返回諾言,而不是立即值,但您將始終照顧成功/錯誤,並采用一致的方式處理數據流。

除了AJAX請求之外,還有更多的異步源,我真的想不到在Java中需要同步返回值的情況。

我想盡可能使它異步,這是否意味着我必須使這段代碼鏈中的所有內容都消耗掉並返回承諾?

是。 可能異步的事物必須始終返回promise,並且必須始終被消費,就像它是異步的一樣(承諾仍會強制執行)。

是僅發出同步AJAX請求的唯一其他選擇嗎?

是的,您真的不想要那樣。

有更好的選擇嗎? 我在考慮C#的await關鍵字,但是我確定其他語言也具有類似的功能。

實際上, 異步等待也正在ECMAScript中出現。 但這並不能使任何事情同步,而只是到處實現諾言的語法糖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM