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

The use of Promise in JavaScript

高洛峰
Release: 2018-05-15 17:35:36
Original
1365 people have browsed it

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!

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