Home > Web Front-end > JS Tutorial > Detailed explanation of Angularjs Promise examples

Detailed explanation of Angularjs Promise examples

亚连
Release: 2018-05-30 10:07:02
Original
1945 people have browsed it

Promise is a constructor. It has all, reject, and resolve methods for asynchronously processing values. The prototype has then, catch, and other familiar methods. Let’s explain angularjs promise through example code. Related knowledge, interested friends should take a look together

1. What is Promise

Promise is an object, representing the final possibility of a function The return value or exception thrown is used to process the value asynchronously.

Promise is a constructor. It has all, reject, and resolve methods for asynchronously processing values. The prototype has then, catch, and other familiar methods.

2. Why use Promise

With the Promise object, asynchronous operations can be expressed as a synchronous operation process, avoiding the need for layers Nested callback functions. In addition, Promise objects provide a unified interface, making it easier to control asynchronous operations.

The Promise object has the following two characteristics:

1. The state of the object is not affected by the outside world.

The Promise object represents an asynchronous operation and has three states: Pending (in progress), Resolved (completed) and Rejected (failed). Only the result of the asynchronous operation can determine the current state, and no other operation can change this state.

2. Once the status changes, it will not change again, and this result can be obtained at any time.

There are only two possibilities for the state change of the Promise object: from Pending to Resolved; from Pending to Rejected. As long as these two situations occur, the state will be solidified and will not change again, and will maintain this result.

3. How to create a Promise

First paste a piece of code:

define([
  'angularModule'
],function (app) {
  app.register.service('httpRequestService', ['$http', '$q', function ($http, $q) {
    return{
      request: function (params) {
        var deferred = $q.defer();
        $http({
          method : params.method,
          url : params.url
        }).success(
          function (data) {
            deferred.resolve(data);
          }
        ).error(
          function(data){
            deferred.reject(data);
          }
        );
        return deferred.promise;
      }
    }
  }])
});
Copy after login

Let’s talk about $q service

q service is a Promise implementation that is encapsulated and implemented in AngularJS.

To create a deferred object, you can call the defer() method:

var deferred = $q.defer(); 
//deffered上面暴露了三个方法,以及一个可以用于处理promise的promise属性。 
//promise属性里面又包含了then、catch、finally三个方法
Copy after login

In Promise , three states are defined: waiting state, completion state, and rejection state.

deffered API

1.deffered object method

1.resolve(value) : At the declaration of resolve(), it indicates that the promise object changes from the pending state to resolve.
2.reject(reason): At the point where resolve() is declared, it indicates that the promise object changes from the pending state to rejected.
3.notify(value): When notify() is declared, it indicates the unfulfilled status of the promise object and can be called multiple times before resolve or reject.

2.deffered object attribute

promise: What is finally returned is a new deferred object promise attribute, not the original deferred object. This new Promise object can only observe the state of the original Promise object, and cannot modify the internal state of the deferred object to prevent the task state from being modified externally.

3.Promise API

When a deferred instance is created, a new promise object is created, and the reference can be obtained through deferred.promise.

The purpose of the promise object is to allow the interested part to obtain its execution results when the deferred task is completed.

4.Promise object methods

1.then(errorHandler, fulfilledHandler, progressHandler): The then method is used to monitor the different states of a Promise. The errorHandler monitors the failed status, the fulfilledHandler monitors the fulfilled status, and the progressHandler monitors the unfulfilled (incomplete) status. Additionally, the notify callback may be called zero to more times, providing an indication of progress before resolving or rejecting (resolve and rejected).

2.catch(errorCallback) - a shortcut for promise.then(null, errorCallback)

3.finally(callback) - allows you to observe whether a promise is executed or not Rejected, but doing so does not modify the last value. This can be used to do some work of releasing resources or cleaning up unused objects, regardless of whether the promise is rejected or resolved.

q Several commonly used methods:

  • defer() creates a deferred object, which can execute several common methods, such as resolve, reject, notify, etc.

  • all() Pass in the array of Promise, execute it in batches, and return a promise object

  • when() pass Enter an uncertain parameter, and if it meets the Promise standard, return a promise object.

all() method

This method can be used when executing certain methods in batches. With all, you can perform multiple asynchronous operations in parallel and process all return data in a callback.

Use Promise.all to execute. all receives an array parameter, and the values ​​inside are eventually returned to the Promise object. In this way, three asynchronous operations are executed in parallel, and they will not enter then until they are all executed.

那么,三个异步操作返回的数据哪里去了呢?都在then里面呢,all会把所有异步操作的结果放进一个数组中传给then,就是 下面的results。所以下面代码的输出结果就是:

  var funcA = function(){
        console.log("funcA");
        return "hello,funA";
      }
      var funcB = function(){
        console.log("funcB");
        return "hello,funB";
      }
      $q.all([funcA(),funcB()])
      .then(function(result){
        console.log(result);
      });
Copy after login

执行的结果:

funcA
funcB
Array [ "hello,funA", "hello,funB" ]
Copy after login

when()方法

when方法中可以传入一个参数,这个参数可能是一个值,可能是一个符合promise标准的外部对象。

      var funcA = function(){
        console.log("funcA");
        return "hello,funA";
      }
      $q.when(funcA())
      .then(function(result){
        console.log(result);
      });
Copy after login

当传入的参数不确定时,可以使用这个方法。

hello,funA

四、链式请求

通过then()方法可以实现promise链式调用,因为then方法总是返回一个新的promise。

runAsync1()
.then(function(data){
  console.log(data);
  return runAsync2();
})
.then(function(data){
  console.log(data);
  return runAsync3();
})
.then(function(data){
  console.log(data);
});
function runAsync1(){
  var p = new Promise(function(resolve, reject){
    //做一些异步操作
    setTimeout(function(){
      console.log('异步任务1执行完成');
      resolve('随便什么数据1');
    }, 1000);
  });
  return p;      
}
function runAsync2(){
  var p = new Promise(function(resolve, reject){
    //做一些异步操作
    setTimeout(function(){
      console.log('异步任务2执行完成');
      resolve('随便什么数据2');
    }, 2000);
  });
  return p;      
}
function runAsync3(){
  var p = new Promise(function(resolve, reject){
    //做一些异步操作
    setTimeout(function(){
      console.log('异步任务3执行完成');
      resolve('随便什么数据3');
    }, 2000);
  });
  return p;      
}
Copy after login

运行结果:

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

NodeJS父进程与子进程资源共享原理与实现方法

vue中实现图片和文件上传的示例代码

Vue实现搜索 和新闻列表功能简单范例

The above is the detailed content of Detailed explanation of Angularjs Promise examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template