Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
How can I set a flag from a promise that is contained in a loop, pre-ES8?

What I am trying to achieve is sending a bunch of post requests to a print service, and if any of them fail I want to display a warning message to the user. My current set up has a warning message for each time it fails.

items.forEach(function (item) {

    var data = {
        date: self.getDateTime(),
        barcode: item.barcode,
        description: item.description
    };
    var url = 'http://localhost/print_service'
    $.ajax({
        method: "POST",
        url: url,
        data: JSON.stringify(data),
    }).fail(function () {
        self.display_warning(
            'Failed to connect to printer',
        );
    });
});

I am not able to make use of async / await in this project.

My thought was to just set some flag like printFailed = true, and after the loop just display a message if it is true. However, the fail is of course asyncronous, so the flag is now set when I make that check.

How can I tackle this effectively? Typically I would throw the error and / or flag into a .then(), but I can't do this as it would then still be caught in the loop.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try to use Promise.all:

const requests = items.map(function(item) {
    return $.ajax({
        method: "POST",
        url: 'http://localhost/print_service',
        data: JSON.stringify({
            date: self.getDateTime(),
            barcode: item.barcode,
            description: item.description
        }),
    });
});

Promise.all(requests).catch(function() {
    self.display_warning('Failed to connect to printer', );
});


about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!