search
HomeWeb Front-endJS TutorialDetailed explanation of Angularjs Promise examples

Detailed explanation of Angularjs Promise examples

May 30, 2018 am 10:07 AM
angularjsjavascriptpromise

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;
      }
    }
  }])
});

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三个方法

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);
      });

执行的结果:

funcA
funcB
Array [ "hello,funA", "hello,funB" ]

when()方法

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

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

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

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;      
}

运行结果:

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

相关文章:

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!

Statement
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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use