Search code examples
javascriptnode.jscallbackpromisexmlhttprequest

Using the promise constructor to send back a value to the server


I am using the promise function to promisify XHR and i will like to know how to get the response, and post it back to the server if the response is successful.

I am doing something like this

function createChannel(method, url) {
    return new Promise(function (resolve, reject) {
        xhr.open(method, url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = function () {
        if (xhr.readyState == 4 ) {
            var hashValue = resolve(JSON.parse(xhr.responseText));
            console.log(hashValue);
        }
        else {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        }
    };
    xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
    xhr.send(json);
});
}
createChannel(method, url)
    .then(function (datums) {
    console.log(datums)
}).catch(function (err) {
    console.error('Sorry There Was An Error!', err.statusText);
});

if this createChannel succeed, i will like to take the hashvalue variable, and make a request to the server to get a new value.

.then(function (createChannel) {
    console.log(createChannel);    
});

is this possible using promise? Thank you for the advice.


Solution

  • Inside your .then() handler, you just issue a new request and return that promise, chaining it to the first:

    createChannel(method, url).then(function (datums) {
        console.log(datums);
        // call some other async function here that returns a promise
        return someOtherFunctionThatReturnsAPromise(datums);
    }).then(function(finalResult) {
        console.log(finalResult);        
    }).catch(function (err) {
        console.error('Sorry There Was An Error!', err.statusText);
    })