目前,我对 Promise 的理解只是外部环境(浏览器、node.js 等)原生异步函数的包装器。我对如何实际编写使用 Promise 将异步操作正确连接在一起的软件感到困惑。这是我的问题:
在下面的代码中,setTimeout
函数被包装在一个 Promise 中。我还在 promise 中包装了 XMLHttpRequest
调用。我假设(错误地)如果我按照以下方式将它们链接在一起,则计时器将运行,然后将进行 AJAX 调用。这不会发生。 AJAX 调用首先发生。
timer(1000).then(AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json'))
如果我将 promise 链更改为如下所示,它就会按预期工作!
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
接受一个函数,如果你给它一个 promise ,它将不知道如何处理它。
您可以通过更改传入的内容来解决这个问题 .then
匹配该签名:
timer(1000)
.then(() => AjaxRequest(url1))
.then(() => timer(1000))
.then(() => AjaxRequest(url2))
.then(() => timer(1000));
关于javascript - 如何正确链接包含在 Promise 中的不同异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42923702/