【问题标题】:How to chain different async operations wrapped in promises correctly如何正确链接包装在 Promise 中的不同异步操作
【发布时间】: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
        }


    });
};

【问题讨论】:

标签: javascript ajax asynchronous promise xmlhttprequest


【解决方案1】:

<Promise>.then 接受一个函数,如果你给它一个承诺,它不会知道如何处理它。

您可以通过将传入的内容更改为 .then 以匹配该签名来解决此问题:

timer(1000)
.then(() => AjaxRequest(url1))
.then(() => timer(1000))
.then(() => AjaxRequest(url2))
.then(() => timer(1000));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多