【发布时间】:2017-03-21 09:58:41
【问题描述】:
目前我对 Promise 的理解只是对外部环境(浏览器、node.js 等)原生异步函数的封装。我对如何实际编写使用 Promise 将异步操作正确连接在一起的软件感到困惑。这是我的问题:
在下面的代码中,setTimeout 函数被包装在一个 Promise 中。我还在一个承诺中包装了一个XMLHttpRequest 电话。我假设(错误地)如果我以以下方式将它们链接在一起,计时器将运行并且然后将进行 AJAX 调用。这不会发生。 AJAX 调用首先发生。
timer(1000).then(AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json'))
如果我将我的承诺链更改为如下所示,它将按预期工作!
timer(1000).then(function(){
AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json')
})
前面代码的问题是我正在恢复使用回调来进行异步操作。 我假设有一种方法可以编写我的代码,这样我就不必回到回调,我可以做这样的事情:
timer(1000)
.then(AJAXGetRequest('some/api'))
.then(timer) // wait
.then(AJAXGetRequest('someOther/api'))
.then(timer) // wait
.then(AJAXGetRequest('another/api'))
// wait
甚至更灵活:
timer(1000)
.then(AJAXGetRequest('some/api'))
.then(timer(200)) // wait
.then(AJAXGetRequest('someOther/api'))
.then(timer(600)) // wait
.then(AJAXGetRequest('another/api'))
// wait
以下是前面示例的其余代码:
let timer = function(value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(value);
resolve(value);
}, value);
});
};
let AJAXGetRequest = function(URL) {
return new Promise((resolve, reject) => {
var getRequest = new XMLHttpRequest();
getRequest.open('get', URL, true);
getRequest.send();
getRequest.onload = function() {
var JSONObject = JSON.parse(getRequest.responseText);
console.log(JSONObject);
resolve(JSONObject); // object
}
});
};
【问题讨论】:
-
Promises 从来没有承诺没有回调。
标签: javascript ajax asynchronous promise xmlhttprequest