Promises - Any Method

Video

JavaScript Notes

HTML
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Promise.any</title>
      </head>
      <body>
        <h1>Promise.any()</h1>
        <script src="any.js"></script>
      </body>
    </html>
JavaScript
    // Promise.any - like Promise.race( ) but more forgiving
    // https://node.green/
    // https://caniuse.com/mdn-javascript_builtins_promise_any
    
    let p1 = new Promise((resolve, reject) => {
      reject(1);
    });
    let p2 = new Promise((resolve, reject) => {
      resolve(2);
    });
    let p3 = new Promise((resolve, reject) => {
      reject(3);
    });
    let p4 = new Promise((resolve, reject) => {
      reject(4);
    });
    
    Promise.race([p1, p2, p3, p4])
      .then((resp) => {
        console.log('FIRST of four responses', { resp });
      })
      .catch((err) => {
        console.error(`CATCH ERROR ${err}`);
      });
    
    Promise.any([p1, p2, p3, p4])       // runs when first one that comes back successfully
      .then((resp) => {
        console.log('At least one worked', { resp });
        //resp is the first one that resolved
      })
      .catch((err) => {
        //if all promises are rejected
        console.error(`CATCH ERROR ${err}`);
      });