Domanda

Essentially I have a ton of objects that I want to test the website on. I am using underscore to transform the URL into an array of promises for HTTP requests. As soon as one fails the chain is ending (I expected this). Is it possible for all the failures to be collected and returned to the Fail function? Or am I going to have to write this using allSettled and then parse that?

var Q = require('q')
var _ = require('underscore')
var JSON = require('JSON')
var FS = require("q-io/fs");
var HTTP = require("q-io/http");


FS.read('members.json').then(function(memberJson){
    return JSON.parse(memberJson)
}).then(function(memberObjects){
    var httpCheckPromises = _.
        chain(memberObjects).
        first(100).
        filter(function(member){
            return member.website.toLowerCase().indexOf('www') >= 0
        }).
        map(function(member){
            return HTTP.read(member.website)
        }).
        value()

    return Q.all(httpCheckPromises)
}).then(function(goodRequests){
    console.log(goodRequests)
}).fail(function(badRequests){
    console.log('bad')
    console.log(badRequests)
})
È stato utile?

Soluzione

Am I going to have to write this using allSettled and then parse that?

Yes, if you don't want to abort on the first failed request.

FS.read('members.json')
.then(JSON.parse)
.then(function(memberObjects){
    var httpCheckPromises = _.chain(memberObjects)
        .first(100)
        .pluck("website")
        .filter(function(website){
            return website.toLowerCase().indexOf('www') >= 0;
        })
        .map(HTTP.read)
        .value();
    return Q.allSettled(httpCheckPromises);
}).then(function(requests) {
    var goodRequests = _.chain(requests)
        .where({state:"fulfilled"})
        .pluck("value")
        .value(),
    badRequests = _.chain(requests)
        .where({state:"rejected"})
        .pluck("reason")
        .value();
    console.log("good:", goodRequests);
    console.log("bad:", badRequests);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top