如何链接原生Javascript承诺?

时间:2015-07-16 20:04:41

标签: javascript promise ecmascript-6 fetch-api

我已经阅读了关于JS承诺的所有可以想象的文章,我仍然无法弄清楚它们。我试图使用promises来管理多个XMLHTTPRequests。例如:当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对象中包装每个函数调用,以便我可以控制它们何时被调用?

2 个答案:

答案 0 :(得分: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()
    })
}

答案 1 :(得分:1)

另外,请注意,有一个方便的功能来发出AJAX请求并获得承诺 - window.fetch。 Chrome和Firefox已经支持它,对于其他浏览器,它可以是polyfilled

然后您可以轻松解决您的问题

raw
相关问题