how to ensure request is done sequentially?

119 views Asked by At

I'd like to request one page after another, the following code seems request all the pages in the same time, is there a way to fetch one page after the previous one is done? thanks

var Promise = require("bluebird");
var request = Promise.promisifyAll(require('request'));
var URLS = ["http://sample.com/j1", "http://sample.com/j2"]

Promise.map(URLS, function (item) {
    return request.postAsync({url: item}).spread(function (response,body) {
    var items = JSON.parse(body)
    return items
})
}).then(function (r) {
    console.log(r.length)
})
1

There are 1 answers

0
NG. On BEST ANSWER

You can set the concurrency level, which is specific to bluebird.

Promise.map(URLS, function (item) {
    return request.postAsync({url: item}).spread(function (response,body) {
    var items = JSON.parse(body)
    return items
}, { concurrency: 1})

This will issue all the promises one at a time.