如何在处理数组时退出promise序列?

时间:2016-03-23 19:23:04

标签: javascript node.js promise es6-promise

我在脚本中实现了以下代码示例,该脚本遍历结果数组并为每个结果发出http请求。

function sequence(array, callback) {
    return array.reduce(function chain(promise, item) {
        return promise.then(function () {
            return callback(item);
        });
    }, Promise.resolve());
};

var products = ['sku-1', 'sku-2', 'sku-3'];

sequence(products, function (sku) {
    return getInfo(sku).then(function (info) {
        console.log(info)
    });
}).catch(function (reason) {
    console.log(reason);
});

function getInfo(sku) {
    console.log('Requested info for ' + sku);
    //assume this function makes an http request and returns a  promise
}

一旦处理了数组中的所有项目,脚本就不会退出。我如何调整它以便发生这种情况?

我的实现进行API调用并返回一个promise:

....

}).then(function(results){
sequence(results, function(result){

    checkSpam(result).then(function(akismet){
        if(akismet) {
            //console.log('spam returned from checkspam');
            write_spam_to_file(result);
        } else {

            //console.log('no spam returned from checkspam');
        }
    })
});

}).catch(function (e) {
    console.log('Error occurred:');
    console.log(e);
});


function sequence(array, callback) {
    return array.reduce(function chain(promise, item) {
        return promise.then(function () {
            return callback(item);
        });
    }, Promise.resolve());
}

function checkSpam(entry) {

    var akismetPromise = new Promise(function resolver(resolve, reject) {
        akismet.checkSpam({
            user_agent: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
            referrer: 'http://google.com',
            user_ip: entry.ip,
            comment_author: entry.poster,
            comment_content: entry.message,
            comment_type: 'forum-post'


        }, function (err, spam) {
            if (err) reject(err);
            resolve(spam);
        });

    });
    return akismetPromise;

}

1 个答案:

答案 0 :(得分:3)

与您的第一个代码段相反,您的实际代码缺少一堆return个关键字:

    …
}).then(function(results) {
    return sequence(results, function(result) {
//  ^^^^^^
        return checkSpam(result).then(function(akismet) {
//      ^^^^^^
            if (akismet) {
                return write_spam_to_file(result);
//              ^^^^^^ // assuming the write is asynchronous and returns a promise?
            }
        });
    });
}) …

如果您不是always return a promise来自异步函数(包括then回调),则承诺链不知道要等待什么,并执行下一个回调而无需等待任何结果。