Home Web Front-end JS Tutorial The use of Promise in JavaScript

The use of Promise in JavaScript

May 15, 2018 pm 05:35 PM
promise

Promise is a function in ES6 that specifies how to handle callback functions for asynchronous tasks. Its function is similar to jQuery's defferred. Simply put, different callback functions are called through different states of the promise object. Currently IE8 and below are not supported, but other browsers are.

The state of the promise object will not change after it is converted from Pending to Resolved or Rejected.

Usage steps:

var promise = new Promise(function(resolve, reject) {

 // 异步任务,通过调用resolve(value) 或 reject(error),以改变promise对象的状态;改变状态的方法只能在此调用。

//promise状态改变后,会调用对应的回调方法

});

promise.then(function(value){//resolve时的回调函数,参数由异步的函数传进来})

.catch(function(error){//发生异常时或明确reject()时的回调函数})
Copy after login

Specific usage:

function getURL(URL) {           //因为promise创建时即执行,所以用工厂函数封装promise对象
  return new Promise(function (resolve, reject) {
    var req = new XMLHttpRequest();
    req.open('GET', URL, true);
    req.onload = function () {
      if (req.status === 200) {
        resolve(req.responseText);
      } else {
        reject(new Error(req.statusText));
      }
    };
    req.onerror = function () {
      reject(new Error(req.statusText));
    };
    req.send();
  });
}
// 运行示例
var URL = "http://httpbin.org/get";
getURL(URL).then(function onFulfilled(value){
  console.log(value);
}).catch(function onRejected(error){
  console.error(error);
})
Copy after login

The callback of Promise is only asynchronous, even the callback of a synchronous task is executed asynchronously.

var promise = new Promise(function (resolve){
  console.log("inner promise");         // 执行1:同步任务先执行
  resolve(‘callBack');
});
promise.then(function(value){
  console.log(value);              // 执行3:虽然注册时状态为resolved,但回调仍是异步的;
});
console.log("outer promise");          // 执行2:同步代码先执行
Copy after login

Promise method chain

The callbacks registered by the then method will be called in sequence, and parameters are passed through the return value between each then method. However, exceptions in the callback will cause the then callback to be skipped, the catch callback to be called directly, and then the remaining then callbacks to be called. In then(onFulfilled, onRejected), the onFulfilled exception will not be caught by its own onRejected, so catch is used first.

promise .then(taskA) .then(taskB) .catch(onRejected) .then(finalTask);

taskA throws an exception, taskB is skipped, and finalTask ​​will still be called, because The status of the promise object returned by catch is resolved.

The then method can return 3 kinds of values

1. Return another promise object. The next then method selects the onFullfilled/onRejected callback function to execute according to its status. The parameters are still determined by the resolv of the new promise. /reject method delivery;

2. Returns a synchronous value. The next then method uses the state of the current promise object and will be executed immediately without waiting for the asynchronous task to end; the actual parameter is the return value of the previous then; if not return, the default return is undefined;

3. Throw an exception (synchronous/asynchronous): throw new Error('xxx');

then not only registers a callback function, but also The return value of the callback function is transformed, creating and returning a new promise object. In fact, Promise does not operate on the same promise object in the method chain.

var aPromise = new Promise(function (resolve) {
  resolve(100);
});
var thenPromise = aPromise.then(function (value) {
  console.log(value);
});
var catchPromise = thenPromise.catch(function (error) {
  console.error(error);
});
console.log(aPromise !== thenPromise); // => true
console.log(thenPromise !== catchPromise);// => true
Copy after login

Promise.all() static method, perform multiple asynchronous tasks at the same time. Subsequent processing will not continue until all received promise objects become FulFilled or Rejected.

Promise.all([promiseA, promiseB]).then(function(results){//results是个数组,元素值和前面promises对象对应});

// 由promise对象组成的数组会同时执行,而不是一个一个顺序执行,开始时间基本相同。
function timerPromisefy(delay) {
  console.log('开始时间:”'+Date.now()) 
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(delay);
    }, delay);
  });
}
var startDate = Date.now();
Promise.all([
  timerPromisefy(100),    //promise用工厂形式包装一下
  timerPromisefy(200),
  timerPromisefy(300),
  timerPromisefy(400)
]).then(function (values) {
  console.log(values);  // [100,200,300,400]
});
Copy after login

Does not execute simultaneously, but executes promises one after another

//promise factories返回promise对象,只有当前异步任务结束时才执行下一个then
function sequentialize(promiseFactories) {
  var chain = Promise.resolve();
  promiseFactories.forEach(function (promiseFactory) {
    chain = chain.then(promiseFactory);
  });
  return chain;
}
Copy after login

Promise.race() is similar to all(), but race() only needs one promise object to enter the FulFilled or Rejected state If so, the corresponding callback function will be executed. However, after the first promise object becomes Fulfilled, it does not affect the continued execution of other promise objects.

//沿用Promise.all()的例子
Promise.race([
  timerPromisefy(1),
  timerPromisefy(32),
  timerPromisefy(64),
  timerPromisefy(128)
]).then(function (value) {
  console.log(values);  // [1]
});
Copy after login

The wonderful use of Promise.race() as a timer

Promise.race([
  new Promise(function (resolve, reject) {
    setTimeout(reject, 5000);     // timeout after 5 secs
  }),
  doSomethingThatMayTakeAwhile()
]);
Copy after login

Changing the promise state in then

Because there are only value parameters in the callback of then, there is no way to change the state (Can only be used in the asynchronous task of the constructor). If you want to change the state of the promise object passed to the next then, you can only create a new Promise object, determine whether to change the state in the asynchronous task, and finally return it to pass. Give the next then/catch.

var promise = Promise.resolve(‘xxx');//创建promise对象的简介方法
promise.then(function (value) {
  var pms=new Promise(function(resolve,reject){
    setTimeout(function () {
      // 在此可以判断是否改变状态reject/resolve
      Reject(‘args');
    }, 1000);
  })
  return pms;  //该promise对象可以具有新状态,下一个then/catch需要等异步结束才会执行回调;如果返回普通值/undefined,之后的then/catch会立即执行
}).catch(function (error) {
  // 被reject时调用
  console.log(error)
});
Copy after login

Get the results of two promises

//方法1:通过在外层的变量传递
var user;
getUserByName('nolan').then(function (result) {
  user = result;
  return getUserAccountById(user.id);
}).then(function (userAccount) {
  //可以访问user和userAccount
});

//方法2:后一个then方法提到前一个回调中
getUserByName('nolan').then(function (user) {
  return getUserAccountById(user.id).then(function (userAccount) {
    //可以访问user和userAccount
  });
});
Copy after login

Pay attention to the overall structure when using promise

Assume that both doSomething() and doSomethingElse() return promise objects

Commonly used methods:

doSomething().then(doSomethingElse).then(finalHandler);
doSomething
|-----------------|
         doSomethingElse(resultOfDoSomething)  //返回新promise,下一个then要收到新状态才执行
         |------------------|
                   finalHandler(resultOfDoSomethingElse)
                   |---------------------|
Copy after login

Commonly used workarounds:

doSomething().then(function () { return doSomethingElse();}).then(finalHandler);
doSomething
|-----------------|
         doSomethingElse(undefined) //then外层函数的arguments[0]== resultOfDoSomething
         |------------------|
                   finalHandler(resultOfDoSomethingElse)
                   |------------------|
Copy after login

Error method 1:

doSomething().then(function () { doSomethingElse();}).then(finalHandler);
doSomething
|-----------------|
         doSomethingElse(undefined)  //虽然doSomethingElse会返回promise对象,但最外层的回调函数是return undefined,所以下一个then方法无需等待新promise的状态,会马上执行回调。
         |------------------|
         finalHandler(undefined)
         |------------------|
Copy after login

Error method 2:

doSomething().then(doSomethingElse()).then(finalHandler);
doSomething
|-----------------|
doSomethingElse(undefined)     //回调函数在注册时就直接被调用
|----------|
         finalHandler(resultOfDoSomething)
         |------------------|
Copy after login

More Promises in JavaScript For articles related to the use of PHP, please pay attention to the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

What should I do if I encounter Uncaught (in promise) TypeError in a Vue application? What should I do if I encounter Uncaught (in promise) TypeError in a Vue application? Jun 25, 2023 pm 06:39 PM

Vue is a popular front-end framework, and you often encounter various errors and problems when developing applications. Among them, Uncaught(inpromise)TypeError is a common error type. In this article, we will discuss its causes and solutions. What is Uncaught(inpromise)TypeError? Uncaught(inpromise)TypeError error usually appears in

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Example analysis of the principle and use of ES6 Promise Example analysis of the principle and use of ES6 Promise Aug 09, 2022 pm 03:49 PM

Use Promise objects to change ordinary functions to return Promise to solve the problem of callback hell. Understand the success and failure calling logic of Promise and make adjustments flexibly. Understand the core knowledge, use it first, and slowly integrate and absorb the knowledge.

Which browsers support Promise? Which browsers support Promise? Feb 19, 2024 pm 04:41 PM

Browser compatibility: Which browsers support Promises? As the complexity of web applications continues to increase, developers are eager to solve the problem of asynchronous programming in JavaScript. In the past, developers often used callback functions to handle asynchronous operations, but this resulted in code that was complex and difficult to maintain. To solve this problem, ECMAScript6 introduced Promise, which provides a more intuitive and flexible way to handle asynchronous operations. Promise is a method used to handle exceptions

What are promise objects? What are promise objects? Nov 01, 2023 am 10:05 AM

The promise object states are: 1. pending: initial state, neither success nor failure state; 2. fulfilled: means the operation was successfully completed; 3. rejected: means the operation failed. Once a Promise object is completed, it will change from the pending state to the fulfilled or rejected state, and cannot change again. Promise objects are widely used in JavaScript to handle asynchronous operations such as AJAX requests and timed operations.

What are the advantages of PHP functions returning Promise objects? What are the advantages of PHP functions returning Promise objects? Apr 19, 2024 pm 05:03 PM

Advantages: asynchronous and non-blocking, does not block the main thread; improves code readability and maintainability; built-in error handling mechanism.

What does promise mean? What does promise mean? Nov 02, 2023 pm 05:30 PM

Promise is a programming pattern for handling asynchronous operations. It is an object that represents the final completion or failure of an asynchronous operation. It can be seen as a commitment to asynchronous operations. It can better manage and organize asynchronous code. , making the code more readable and maintainable. Promise objects have three states: pending, fulfilled and rejected. The core idea of ​​Promise is to separate asynchronous operations from callback functions and express the dependencies between asynchronous operations through chain calls.

See all articles