4

我已经阅读了所有可以想象到的关于 JS 承诺的文章,但我仍然无法弄清楚它们。我正在尝试使用承诺来管理多个 XMLHTTPRequest。eg: 当xhr 请求1 & 2 完成时,调用这个函数。

示例代码:

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
}

在这种情况下,我将如何将每个函数调用包装在一个 Promise 对象中,以便我可以控制它们何时被调用?

4

2 回答 2

2

使用回调,您总是通过一个函数“响应”。例如:

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

Promises 让你根据当前状态做出响应:

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

这使“回调金字塔”变平。代替

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

您可以使用:

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

所以,要回答你的问题,首先你要为你的 http 请求使用一个承诺:

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

然后,您希望将其合并到您的loadRates函数中:

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

然后,在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()
    })
}
于 2015-07-16T21:03:11.530 回答
1

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)
})
于 2015-07-17T20:35:44.750 回答