簡體   English   中英

如何使用setTimeout和promises使此JS代碼更具功能性?

[英]How can I make this JS code more functional using setTimeout and promises?

我正在嘗試學習如何使用更多的功能和更少的循環以及以更多的功能方式進行編碼。 我想在調用connectBing之間實現超時。 我想知道是否有可能不使用i變量,而在兩次迭代之間仍然有1秒的超時時間。 我的代碼當前有效,但是我正在尋找其他方法而不使用i。

這是我的代碼:

// MAIN
getAllPosts().then((posts) => {
    posts
        .forEach( (post, i) => {
            setTimeout(() => {
                connectBing(anchorText,console.log).then()
            } ,i * 1000)
        })

// CONNECT TO BING WITH KW AND DO SOMETHING
function connectBing(anchorText,doSomethingWithBing) {
    var deferred = q.defer();                                                                   
    request('https://www.cnn.com/search?q=' + anchorText, function (error, response, body) {    
        error ? console.log('error:', error) :                                                    
        console.log('statusCode:', response && response.statusCode);                              
        (doSomethingWithBing) ? doSomethingWithBing(body) : "You didn't give connectBing anything to do!"       
    })
    return deferred.promise                 
}

您可以采用一系列異步函數,並將每個函數鏈接在一起,以在另一個函數之后運行。 我將使用原生的Promise進行演示,您可以將其映射到您正在使用的庫中。

首先創建一個函數,該函數接受一系列異步功能。 它將一個接一個地鏈接,返回最后一個:

function chainAsyncFns(fns) {
    // Ensure we have at least one promise to return

    let promise = Promise.resolve();

    fns.forEach(fn => promise = promise.then(fn));

    return promise;
}

然后為每個帖子創建一個異步函數,該函數將調用connectBing ,然后等待超時:

function connectBing() {
    // Pretend we are connecting to a data source

    return Promise.resolve();
}

function delay(ms) {
    // Return a promise that resolves when the timeout is up

    return new Promise(resolve => setTimeout(resolve, ms));
}

let fns = posts.map(post => () => {
    return connectBing()
        .then(() => delay(1000))
        .catch(() => console.log('error'));
});

鏈接函數以一個接一個地運行:

chainAsyncFns(fns).then(() => console.log('done'));

暫無
暫無

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

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