首頁  >  文章  >  web前端  >  以下是一些適合所提供文章的問題式標題: * 如何使用 Promise 鏈實現同步執行:簡化 `promiseWhile` 和陣列縮減技術指南 * S

以下是一些適合所提供文章的問題式標題: * 如何使用 Promise 鏈實現同步執行:簡化 `promiseWhile` 和陣列縮減技術指南 * S

Linda Hamilton
Linda Hamilton原創
2024-10-28 11:52:00707瀏覽

Here are a few question-style titles that fit the provided article:

* How to Achieve Synchronous Execution with Promise Chains: A Guide to Simplified `promiseWhile` and Array Reduction Techniques
* Synchronous Promise Loops Made Easy:  `PromiseWhile` and

如何使用Promise 鏈建立同步循環

問題:

問題:

問題:
<code class="javascript">var Promise = require('bluebird');

var promiseWhile = function(condition, action) {
    var resolver = Promise.defer();

    var loop = function() {
        if (!condition()) return resolver.resolve();
        return Promise.cast(action())
            .then(loop)
            .catch(resolver.reject);
    };

    loop();

    return resolver.promise;
};</code>

解決方案 1(簡化的 PromiseWhile 函數):

這個簡化版本的 PromiseWhile 函數需要將回呼傳遞為條件和操作參數的參數。
<code class="javascript">function fetchUserDetails(arr) {
    return arr.reduce(function(promise, email) {
        return promise.then(function() {
            return db.getUser(email).done(function(res) {
                logger.log(res);
            });
        });
    }, Promise.resolve());
}</code>

解決方案2(使用數組縮減):

另一種方法是縮減電子郵件地址數組並進行相應的異步調用每個:

此方法建立一個平坦的.then() 鏈並保持反應的原始順序。
<code class="javascript">fetchUserDetails(arrayOfEmailAddys).then(function() {
    console.log('all done');
});</code>

用法:呼叫fetchUserDetails 需要一組電子郵件地址:這種方法消除了對外部計數器或條件函數的需要。此限制由電子郵件數組的長度決定。

以上是以下是一些適合所提供文章的問題式標題: * 如何使用 Promise 鏈實現同步執行:簡化 `promiseWhile` 和陣列縮減技術指南 * S的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn