Promise all with inner function to be executed









up vote
1
down vote

favorite












I want to retrieve different HTML body at once and as soon as all results are available work with that content.



My callback solution which works looks like this (probably only relevant to read if the idea is not clear, otherwise skip ;)):



const request = require('request')

const argLength = process.argv.length
const result_array =
let counter = 0

function executeRequest ()
for (start = 2; start <= argLength - 1; start++)
const copy = start

function callback (error, res, body)
const startCopy = copy
if (error)
console.log('error')
return

result_array[startCopy - 2] = body.toString().length
counter++
if (counter === argLength - 2)
console.log(result_array)



request(process.argv[start], callback)



executeRequest()


Now I try to make it running with Promises like this:



const httpRequest = require('request')
const argumentLength = process.argv.length

function fillURLArray ()
resultArray =
for (start = 2; start < argumentLength; start++)
resultArray[start - 2] = process.argv[start]

return resultArray


const urls = fillURLArray()

let counter = 0

function readHttp ()
const resultArray =
Promise.all(urls.map(url => httpRequest(url, (error, res, body) =>
console.log(body.toString())
resultArray[counter++] = body.toString()
))).then(value =>
console.log('promise counter: ' + counter++)
console.log(resultArray)
console.log('called')
)


readHttp()


I tried already several attempts with different promise chains but every time I get either not a result or just an empty array. So obviously the .then() function is called before the array is actually filled (at least I guess so since console.log(body.toString()) appears to print the content some time later)



Any idea how to solve this with promises?



Thank you










share|improve this question



















  • 1




    npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
    – charlietfl
    Nov 10 at 15:57














up vote
1
down vote

favorite












I want to retrieve different HTML body at once and as soon as all results are available work with that content.



My callback solution which works looks like this (probably only relevant to read if the idea is not clear, otherwise skip ;)):



const request = require('request')

const argLength = process.argv.length
const result_array =
let counter = 0

function executeRequest ()
for (start = 2; start <= argLength - 1; start++)
const copy = start

function callback (error, res, body)
const startCopy = copy
if (error)
console.log('error')
return

result_array[startCopy - 2] = body.toString().length
counter++
if (counter === argLength - 2)
console.log(result_array)



request(process.argv[start], callback)



executeRequest()


Now I try to make it running with Promises like this:



const httpRequest = require('request')
const argumentLength = process.argv.length

function fillURLArray ()
resultArray =
for (start = 2; start < argumentLength; start++)
resultArray[start - 2] = process.argv[start]

return resultArray


const urls = fillURLArray()

let counter = 0

function readHttp ()
const resultArray =
Promise.all(urls.map(url => httpRequest(url, (error, res, body) =>
console.log(body.toString())
resultArray[counter++] = body.toString()
))).then(value =>
console.log('promise counter: ' + counter++)
console.log(resultArray)
console.log('called')
)


readHttp()


I tried already several attempts with different promise chains but every time I get either not a result or just an empty array. So obviously the .then() function is called before the array is actually filled (at least I guess so since console.log(body.toString()) appears to print the content some time later)



Any idea how to solve this with promises?



Thank you










share|improve this question



















  • 1




    npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
    – charlietfl
    Nov 10 at 15:57












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I want to retrieve different HTML body at once and as soon as all results are available work with that content.



My callback solution which works looks like this (probably only relevant to read if the idea is not clear, otherwise skip ;)):



const request = require('request')

const argLength = process.argv.length
const result_array =
let counter = 0

function executeRequest ()
for (start = 2; start <= argLength - 1; start++)
const copy = start

function callback (error, res, body)
const startCopy = copy
if (error)
console.log('error')
return

result_array[startCopy - 2] = body.toString().length
counter++
if (counter === argLength - 2)
console.log(result_array)



request(process.argv[start], callback)



executeRequest()


Now I try to make it running with Promises like this:



const httpRequest = require('request')
const argumentLength = process.argv.length

function fillURLArray ()
resultArray =
for (start = 2; start < argumentLength; start++)
resultArray[start - 2] = process.argv[start]

return resultArray


const urls = fillURLArray()

let counter = 0

function readHttp ()
const resultArray =
Promise.all(urls.map(url => httpRequest(url, (error, res, body) =>
console.log(body.toString())
resultArray[counter++] = body.toString()
))).then(value =>
console.log('promise counter: ' + counter++)
console.log(resultArray)
console.log('called')
)


readHttp()


I tried already several attempts with different promise chains but every time I get either not a result or just an empty array. So obviously the .then() function is called before the array is actually filled (at least I guess so since console.log(body.toString()) appears to print the content some time later)



Any idea how to solve this with promises?



Thank you










share|improve this question















I want to retrieve different HTML body at once and as soon as all results are available work with that content.



My callback solution which works looks like this (probably only relevant to read if the idea is not clear, otherwise skip ;)):



const request = require('request')

const argLength = process.argv.length
const result_array =
let counter = 0

function executeRequest ()
for (start = 2; start <= argLength - 1; start++)
const copy = start

function callback (error, res, body)
const startCopy = copy
if (error)
console.log('error')
return

result_array[startCopy - 2] = body.toString().length
counter++
if (counter === argLength - 2)
console.log(result_array)



request(process.argv[start], callback)



executeRequest()


Now I try to make it running with Promises like this:



const httpRequest = require('request')
const argumentLength = process.argv.length

function fillURLArray ()
resultArray =
for (start = 2; start < argumentLength; start++)
resultArray[start - 2] = process.argv[start]

return resultArray


const urls = fillURLArray()

let counter = 0

function readHttp ()
const resultArray =
Promise.all(urls.map(url => httpRequest(url, (error, res, body) =>
console.log(body.toString())
resultArray[counter++] = body.toString()
))).then(value =>
console.log('promise counter: ' + counter++)
console.log(resultArray)
console.log('called')
)


readHttp()


I tried already several attempts with different promise chains but every time I get either not a result or just an empty array. So obviously the .then() function is called before the array is actually filled (at least I guess so since console.log(body.toString()) appears to print the content some time later)



Any idea how to solve this with promises?



Thank you







javascript node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 22:15









marc_s

565k12510911243




565k12510911243










asked Nov 10 at 15:50









AnnaKlein

502222




502222







  • 1




    npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
    – charlietfl
    Nov 10 at 15:57












  • 1




    npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
    – charlietfl
    Nov 10 at 15:57







1




1




npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
– charlietfl
Nov 10 at 15:57




npm request does not return promises so array you pass to Promise.all() is not array of promises. Use one of the request libraries that includes promises npmjs.com/package/request#promises--asyncawait
– charlietfl
Nov 10 at 15:57












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










request is not returning promise object so have created a method that return promise object on which you do Promise.all.



function requestPromise(url)
return new Promise((resovle,reject) =>
httpRequest(url, (error, res, body) =>
if(err)
reject(err);

resolve(body.toString());
);
);



function readHttp ()
const resultArray =
Promise.all(urls.map(url => requestPromise(url))).then(values =>
console.log("counter => ",values.length);
resultArray = resultArray.concat(values);
console.log("values=> ",values);
console.log("resultArray=> ",resultArray);
);






share|improve this answer






















  • I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
    – AnnaKlein
    Nov 10 at 15:56











  • @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
    – front_end_dev
    Nov 10 at 16:01










  • @AnnaKlein updated my answer to support promise.
    – front_end_dev
    Nov 10 at 16:32

















up vote
1
down vote













httpRequest does not return a promise so you have to make one yourself, also your resultArray is not necessary:



 const makeRequest = url => new Promise((resolve, reject) => httpRequest(url, (error, res) => error ? reject(error) : resolve(res)));

Promise.all(urls.map(makeRequest))
.then(result =>
console.log(result.map(res => res.body.toString()));
console.log('called');
);





share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240622%2fpromise-all-with-inner-function-to-be-executed%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    request is not returning promise object so have created a method that return promise object on which you do Promise.all.



    function requestPromise(url)
    return new Promise((resovle,reject) =>
    httpRequest(url, (error, res, body) =>
    if(err)
    reject(err);

    resolve(body.toString());
    );
    );



    function readHttp ()
    const resultArray =
    Promise.all(urls.map(url => requestPromise(url))).then(values =>
    console.log("counter => ",values.length);
    resultArray = resultArray.concat(values);
    console.log("values=> ",values);
    console.log("resultArray=> ",resultArray);
    );






    share|improve this answer






















    • I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
      – AnnaKlein
      Nov 10 at 15:56











    • @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
      – front_end_dev
      Nov 10 at 16:01










    • @AnnaKlein updated my answer to support promise.
      – front_end_dev
      Nov 10 at 16:32














    up vote
    1
    down vote



    accepted










    request is not returning promise object so have created a method that return promise object on which you do Promise.all.



    function requestPromise(url)
    return new Promise((resovle,reject) =>
    httpRequest(url, (error, res, body) =>
    if(err)
    reject(err);

    resolve(body.toString());
    );
    );



    function readHttp ()
    const resultArray =
    Promise.all(urls.map(url => requestPromise(url))).then(values =>
    console.log("counter => ",values.length);
    resultArray = resultArray.concat(values);
    console.log("values=> ",values);
    console.log("resultArray=> ",resultArray);
    );






    share|improve this answer






















    • I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
      – AnnaKlein
      Nov 10 at 15:56











    • @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
      – front_end_dev
      Nov 10 at 16:01










    • @AnnaKlein updated my answer to support promise.
      – front_end_dev
      Nov 10 at 16:32












    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    request is not returning promise object so have created a method that return promise object on which you do Promise.all.



    function requestPromise(url)
    return new Promise((resovle,reject) =>
    httpRequest(url, (error, res, body) =>
    if(err)
    reject(err);

    resolve(body.toString());
    );
    );



    function readHttp ()
    const resultArray =
    Promise.all(urls.map(url => requestPromise(url))).then(values =>
    console.log("counter => ",values.length);
    resultArray = resultArray.concat(values);
    console.log("values=> ",values);
    console.log("resultArray=> ",resultArray);
    );






    share|improve this answer














    request is not returning promise object so have created a method that return promise object on which you do Promise.all.



    function requestPromise(url)
    return new Promise((resovle,reject) =>
    httpRequest(url, (error, res, body) =>
    if(err)
    reject(err);

    resolve(body.toString());
    );
    );



    function readHttp ()
    const resultArray =
    Promise.all(urls.map(url => requestPromise(url))).then(values =>
    console.log("counter => ",values.length);
    resultArray = resultArray.concat(values);
    console.log("values=> ",values);
    console.log("resultArray=> ",resultArray);
    );







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 10 at 16:31

























    answered Nov 10 at 15:53









    front_end_dev

    1,310411




    1,310411











    • I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
      – AnnaKlein
      Nov 10 at 15:56











    • @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
      – front_end_dev
      Nov 10 at 16:01










    • @AnnaKlein updated my answer to support promise.
      – front_end_dev
      Nov 10 at 16:32
















    • I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
      – AnnaKlein
      Nov 10 at 15:56











    • @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
      – front_end_dev
      Nov 10 at 16:01










    • @AnnaKlein updated my answer to support promise.
      – front_end_dev
      Nov 10 at 16:32















    I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
    – AnnaKlein
    Nov 10 at 15:56





    I tried this already. The problem here is that the returned array has only one entry. But it should has as much as urls are delivered.
    – AnnaKlein
    Nov 10 at 15:56













    @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
    – front_end_dev
    Nov 10 at 16:01




    @AnnaKlein I think charlietfl has answer your question. request is not returning promise object. So go with this npm module - github.com/request/request-promise to handle promise wtih request
    – front_end_dev
    Nov 10 at 16:01












    @AnnaKlein updated my answer to support promise.
    – front_end_dev
    Nov 10 at 16:32




    @AnnaKlein updated my answer to support promise.
    – front_end_dev
    Nov 10 at 16:32












    up vote
    1
    down vote













    httpRequest does not return a promise so you have to make one yourself, also your resultArray is not necessary:



     const makeRequest = url => new Promise((resolve, reject) => httpRequest(url, (error, res) => error ? reject(error) : resolve(res)));

    Promise.all(urls.map(makeRequest))
    .then(result =>
    console.log(result.map(res => res.body.toString()));
    console.log('called');
    );





    share|improve this answer
























      up vote
      1
      down vote













      httpRequest does not return a promise so you have to make one yourself, also your resultArray is not necessary:



       const makeRequest = url => new Promise((resolve, reject) => httpRequest(url, (error, res) => error ? reject(error) : resolve(res)));

      Promise.all(urls.map(makeRequest))
      .then(result =>
      console.log(result.map(res => res.body.toString()));
      console.log('called');
      );





      share|improve this answer






















        up vote
        1
        down vote










        up vote
        1
        down vote









        httpRequest does not return a promise so you have to make one yourself, also your resultArray is not necessary:



         const makeRequest = url => new Promise((resolve, reject) => httpRequest(url, (error, res) => error ? reject(error) : resolve(res)));

        Promise.all(urls.map(makeRequest))
        .then(result =>
        console.log(result.map(res => res.body.toString()));
        console.log('called');
        );





        share|improve this answer












        httpRequest does not return a promise so you have to make one yourself, also your resultArray is not necessary:



         const makeRequest = url => new Promise((resolve, reject) => httpRequest(url, (error, res) => error ? reject(error) : resolve(res)));

        Promise.all(urls.map(makeRequest))
        .then(result =>
        console.log(result.map(res => res.body.toString()));
        console.log('called');
        );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 16:30









        Jonas Wilms

        52.2k42445




        52.2k42445



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240622%2fpromise-all-with-inner-function-to-be-executed%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            ReactJS Fetched API data displays live - need Data displayed static

            政党