How do I double-answer a promise?

  • 0
    tell me how to make xhr1 also received an answer? how is promise to do it? only the first answer comes, and sends the first answer to the second call.

    let myPromise = new Promise(function(myResolve, myReject) {
            let xhr = new XMLHttpRequest();
            let xhr1 = new XMLHttpRequest();
    
            xhr.open(`GET`, `style.css`);
            xhr1.open(`GET`, `xmlData.html`);
    
            xhr.onload = function () {
                if (xhr.status === 200 && xhr.readyState === 4) {
                    myResolve(xhr.responseText);
                }
                else {
                    myReject("Error");
                }
            }
            xhr1.onload = function () {
                if (xhr1.status === 200 && xhr1.readyState === 4) {
                    myResolve(xhr1.responseText);
                }
                else {
                    myReject("Error");
                }
            }
            xhr.send();
            xhr1.send();
        });
    
        myPromise.then(
            function(value) {console.log(value);}
        );
        myPromise.then(
            function(secondValue) {console.log(secondValue);}
        );
    
        myPromise.catch(
            function (error) {
                console.log(error);
            }
        )
        myPromise.catch(
            function (error) {
                console.log(error);
            }
        )


    JavaScript Hanna Mora, Sep 18, 2019

  • 2 Answers
  • 0
    Two asynchronous actions - two promises, one for each. You can combine several later through Promise.all :

    function XMLHttpPromise(method, url, data) {
    return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = () => {
    if (xhr.status === 200 && xhr.readyState === 4)
    resolve(xhr.responseText);
    else
    reject("Error");
    }
    xhr.onerror = xhr.ontimeout = reject;
    xhr.send(data);
    })
    }

    Promise.all([
    XMLHttpPromise('GET', `style.css`),
    XMLHttpPromise('GET', `xmlData.html`)
    ]).then(([value, secondValue]) => {
    console.log(value);
    console.log(secondValue);
    }).catch(console.error);
    Anonymous

  • 0

    1. Throw away the XMLHttpRequest

    2. Use fetch

    3. Promise.all([fetch(`style.css`), fetch(`xmlData.html`)]).then( ... оба запроса завершены )


    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!