函数then()在JavaScript中意味着什么? [英] What does the function then() mean in JavaScript?

查看:175
本文介绍了函数then()在JavaScript中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直看到的代码如下:

I’ve been seeing code that looks like:

myObj.doSome("task").then(function(env) {
    // logic
});

那里()来自哪里?

推荐答案

在JavaScript中处理异步调用的传统方法是使用回调。
假设我们必须一个接一个地调用服务器来设置我们的
应用程序。使用回调,代码可能类似于以下内容(假设
a xhrGET函数来进行服务器调用):

The traditional way to deal with asynchronous calls in JavaScript has been with callbacks. Say we had to make three calls to the server, one after the other, to set up our application. With callbacks, the code might look something like the following (assuming a xhrGET function to make the server call):

// Fetch some server configuration
    xhrGET('/api/server-config', function(config) {
        // Fetch the user information, if he's logged in
        xhrGET('/api/' + config.USER_END_POINT, function(user) {
            // Fetch the items for the user
            xhrGET('/api/' + user.id + '/items', function(items) {
                // Actually display the items here
            });
        });
    });

在本例中,我们首先获取服务器配置。然后基于此,我们获取有关当前用户的
信息,然后最终获取当前
用户的项目列表。每个xhrGET调用都采用一个回调函数,该函数在服务器
响应时执行。

In this example, we first fetch the server configuration. Then based on that, we fetch information about the current user, and then finally get the list of items for the current user. Each xhrGET call takes a callback function that is executed when the server responds.

现在我们拥有的嵌套级别越多,代码越难阅读,调试,
维护,升级,基本上可以使用。这通常被称为回调地狱。
另外,如果我们需要处理错误,我们需要将另一个函数传递给每个
xhrGET调用,以告诉它在发生错误时需要做什么。如果我们想要只有一个
常见错误处理程序,那是不可能的。

Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as callback hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.


Promise API旨在解决这个问题嵌套问题和错误处理的
问题。

The Promise API was designed to solve this nesting problem and the problem of error handling.

Promise API提出以下建议:

The Promise API proposes the following:


  1. 每个异步任务都将返回 promise 对象。

  2. 每个 promise 对象将有一个然后函数,它可以带两个参数,一个 success
    处理程序和错误处理程序。

  3. 成功错误处理程序在然后函数只会被调用一次,在异步任务完成
    之后。

  4. 然后函数还将返回承诺,以允许链接多个电话。

  5. 每个处理程序(成功或错误)都可以返回,它将作为<$ c传递给下一个
    函数$ c>参数,在承诺链中 s。

  6. 如果处理程序返回 promise (发出另一个异步请求),然后只有在该请求完成后才会调用下一个
    处理程序(成功或错误)。

  1. Each asynchronous task will return a promise object.
  2. Each promise object will have a then function that can take two arguments, a success handler and an error handler.
  3. The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
  4. The then function will also return a promise, to allow chaining multiple calls.
  5. Each handler (success or error) can return a value, which will be passed to the next function as an argument, in the chain of promises.
  6. If a handler returns a promise (makes another asynchronous request), then the next handler (success or error) will be called only after that request is finished.

因此前面的示例代码可能会转换为类似以下的内容,使用
promises和 $ http 服务(在AngularJs中):

So the previous example code might translate to something like the following, using promises and the $http service(in AngularJs):

$http.get('/api/server-config').then(
    function(configResponse) {
        return $http.get('/api/' + configResponse.data.USER_END_POINT);
    }
).then(
    function(userResponse) {
        return $http.get('/api/' + userResponse.data.id + '/items');
    }
).then(
    function(itemResponse) {
        // Display items here
    }, 
    function(error) {
        // Common error handling
    }
);

传播成功和错误

链接承诺是一种非常强大的技术,它允许我们完成许多
功能,比如让服务进行服务器调用,对
数据进行一些后处理,然后返回处理后的数据到控制器。但是当我们使用
promise 链时,我们需要记住一些事项。

Chaining promises is a very powerful technique that allows us to accomplish a lot of functionality, like having a service make a server call, do some postprocessing of the data, and then return the processed data to the controller. But when we work with promise chains, there are a few things we need to keep in mind.

考虑以下假设的承诺链,其中包含三个承诺,P1,P2和P3。
每个承诺都有一个成功处理程序和一个错误处理程序,因此S1和S1用于P1,S2和
E2用于P2,S3和E3用于P3:

Consider the following hypothetical promise chain with three promises, P1, P2, and P3. Each promise has a success handler and an error handler, so S1 and E1 for P1, S2 and E2 for P2, and S3 and E3 for P3:

xhrCall()
  .then(S1, E1) //P1
  .then(S2, E2) //P2
  .then(S3, E3) //P3

在没有错误的正常流程中,应用程序将通过S1,S2和最后的S3流动
。但在现实生活中,事情从未如此顺利。 P1可能
遇到错误,或P2可能遇到错误,触发E1或E2。

In the normal flow of things, where there are no errors, the application would flow through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might encounter an error, or P2 might encounter an error, triggering E1 or E2.

考虑以下情况:

•我们在P1中收到服务器的成功响应,但返回的数据不是
正确,或者服务器上没有可用数据(想想空数组)。在这样的
情况下,对于下一个承诺P2,它应该触发错误处理程序E2。

• We receive a successful response from the server in P1, but the data returned is not correct, or there is no data available on the server (think empty array). In such a case, for the next promise P2, it should trigger the error handler E2.

•我们收到承诺P2的错误,触发E2。但是在处理程序中,我们从缓存中获得了
数据,确保应用程序可以正常加载。在这种情况下,
我们可能想要确保在E2之后调用S3。

• We receive an error for promise P2, triggering E2. But inside the handler, we have data from the cache, ensuring that the application can load as normal. In that case, we might want to ensure that after E2, S3 is called.

所以每次我们写成功或错误处理程序,我们需要进行一次调用 - 给出我们的
当前函数,这个承诺是对promise
链中下一个处理程序的成功还是失败?

如果我们想触发链中下一个promise的成功处理程序,我们只需
就可以从成功或错误处理程序中返回一个值

另一方面,如果我们想要触发
链中下一个承诺的错误处理程序,我们可以使用<$ c来实现$ c> deferred object并调用其 reject()方法

If, on the other hand, we want to trigger the error handler for the next promise in the chain, we can do that using a deferred object and calling its reject() method


现在什么是延迟对象?

Now What is deferred object?

jQuery中的延迟对象表示稍后完成的
工作单元,通常是异步的。一旦工作单元
完成, deferred 对象可以设置为已解决或失败。

Deferred objects in jQuery represents a unit of work that will be completed later, typically asynchronously. Once the unit of work completes, the deferred object can be set to resolved or failed.

延迟对象包含 promise 对象。通过 promise 对象
,您可以指定工作单元完成时要发生的事情。你
通过在 promise 对象上设置回调函数来实现。

A deferred object contains a promise object. Via the promise object you can specify what is to happen when the unit of work completes. You do so by setting callback functions on the promise object.

Jquery中的延迟对象: https://api.jquery.com/jquery.deferred/

Deferred objects in Jquery : https://api.jquery.com/jquery.deferred/

AngularJs中的延迟对象: https ://docs.angularjs.org/api/ng/service/ $ q

Deferred objects in AngularJs : https://docs.angularjs.org/api/ng/service/$q

这篇关于函数then()在JavaScript中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆