简体   繁体   中英

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.

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM