目前我对承诺的理解只是外部环境(浏览器,节点等)原生异步函数的包装器.js。我对如何实际编写使用承诺将异步操作正确连接在一起的软件感到困惑。这是我的问题:
在下面的代码中,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
}
});
};
<Promise>.then
接受一个函数,如果你给它一个承诺,它就不知道如何处理它。
您可以通过更改传入的内容来解决此问题.then
以匹配该签名:
timer(1000)
.then(() => AjaxRequest(url1))
.then(() => timer(1000))
.then(() => AjaxRequest(url2))
.then(() => timer(1000));