简体   繁体   中英

How to chain native Javascript Promises?

I've read every imaginable article on JS promises, and I still can't figure them out. I'm attempting to use promises to manage multiple XMLHTTPRequests. eg: When xhr requests 1 & 2 complete, call this function.

Example code:

function initSession(){
  loadRates(0); 
  loadRates(10); 
  buildTable(); 
  // Get all rates from API, save to localStorage, then build the table. 
}


function loadRates(days) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    // save response to localStorage, using a custom variable
    localStorage.setItem("rates" + days, xhr.responseText); 
  };
  xhr.open('GET', url);
  xhr.send();
}

function buildTable() {
  // get data from localStorage
  // write to HTML table
}

In this instance, how would I wrap each function call in a Promise object so that I can control when they are called?

With callbacks, you always "respond" via one function. For example:

function getUsers (age, done) {
    // done has two parameters: err and result
    return User.find({age}, done)
}

Promises lets you respond according to the current state:

function getUsers (age) {
    return new Promise((resolve, reject) => {
        User.find({ age }, function (err, users) {
            return err ? reject(err) : resolve(users) 
        })
    })
}

This flattens the "callback pyramid." Instead of

getUsers(18, function (err, users) {
    if (err) {
        // handle error
    } else {
        // users available
    }
})

You can use:

getUsers(18).then((users) => {
    // `getPetsFromUserIds` returns a promise
    return getPetsFromUserIds(users.map(user => user._id))
}).then((pets) => {
    // pets here
}).catch((err) => {
    console.log(err) // handle error
})

So, to answer your question, first you'd want to use a promise for your http requests:

function GET (url) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()

        xhr.open('GET', url, true)
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                return resolve(xhr.response)
            } else {
                return reject({ status: this.status, text: xhr.statusText })
            }
        }
        xhr.onerror = reject
        xhr.send()
    })
}

Then, you'd want to incorporate this into your loadRates function:

function loadRates (days) {
    var URL = URL_GENERATOR(days)
    return GET(URL).catch((err) => {
        // handle our error first
        console.log(err)
        // decide how you want to handle a lack of data
        return null
    }).then((res) => {
        localStorage.setItem('rates' + days, res)
        return res
    })
}

Then, in initSession :

function initSession () {
    Promise.all([ loadRates(0), loadRates(10) ]).then((results) => {
        // perhaps you don't want to store in local storage,
        // since you'll have access to the results right here
        let [ zero, ten ] = results
        return buildTable()
    })
}

Also, be aware that there is convenient function to make an AJAX-requests and get promise – window.fetch . Chrome and Firefox already supports it, for other browsers it can be polyfilled .

Then you can solve your issue with ease

function loadRates(days) {
    return window.fetch(url).then(function(response) {
        return response.json(); // needed to parse raw response data
    }).then(function(response) {
        localStorage.setItem("rates" + days, response); 
        return response; // this return is mandatory, otherwise further `then` calls will get undefined as argument
    });
}

Promise.all([
   loadRates(0),
   loadRates(1)
]).then(function(rates) {
   return buildTable(rates)
})

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