首页 > 解决方案 > 对如何在 JS 中使用 Promise 感到困惑

问题描述

我是 JS 新手,正在学习 Promise 以及它们如何在 JS 中使用,我想问一些问题。首先,如果你看下面的代码:

var makeRequest = function (url, method) {

    // Create the XHR request
    var request = new XMLHttpRequest();

    // Return it as a Promise
    return new Promise(function (resolve, reject) {

        // Setup our listener to process compeleted requests
        request.onreadystatechange = function () {

            // Only run if the request is complete
            if (request.readyState !== 4) return;

            // Process the response
            if (request.status >= 200 && request.status < 300) {
                // If successful
                resolve(request);
            } else {
                // If failed
                reject({
                    status: request.status,
                    statusText: request.statusText
                });
            }

        };

        // Setup our HTTP request
        request.open(method || 'GET', url, true);

        // Send the request
        request.send();

    });
};

makeRequest('https://some-url.com/posts')
    .then(function (posts) {
        console.log('Success!', posts);
    })
    .catch(function (error) {
        console.log('Something went wrong', error);
    });

我想问的第一个问题是关于 then() 的回调,我的意思是我们在 then() 中使用的回调,比如 then( (data)=>{console.log(data)})。能不能把它想象成我们在promise之前使用的异步回调,也就是一直等待到异步的回调,比如xhr对象完成返回结果。并且,在 promise 中 then() 的回调等待直到 promise 给出结果,这意味着 Promise 有助于将回调函数与异步操作分离。第二个问题,then() 的回调是异步的,我的意思是,它是否也通过事件循环以及承诺包装的异步代码或承诺包装的代码(例如 xhr 对象)运行,是承诺中唯一的异步吗?第三个问题,当我们说函数返回promise的时候,是不是说promise不管有没有resolved都会马上返回。当函数返回承诺时,我能想象这样吗,返回的承诺有点告诉我们“

标签: javascript

解决方案


我可以把then回调想象成一个异步回调,就像我们在 Promise 之前使用的那样吗?

是的。它仍然“只是”一个回调,当 xhr 对象完成并获得其结果时,它会被异步调用。

Promise 有助于将回调函数与异步操作解耦

对,就是这样。您不再需要知道结果的确切来源以及如何获得它 - 您只需有一个承诺并可以使用它来等待结果。

当一个函数返回一个 Promise 时,返回的 Promise 有点告诉我们“请稍等,我保证我会为您提供可以使用 then() 处理的结果”

恰恰。

我的意思是异步的回调then()是否也通过事件循环运行?

是的。除了 XHR 异步解决 promise 之外,所有then回调都保证被异步调用

当我们说一个函数返回一个promise时,这是否意味着无论它是否被resolve,promise都会立即返回?

是的。这是一个可观察的句柄。


推荐阅读