JavaScript Promise 和 Promise 链

x33g5p2x  于2022-05-16 转载在 Java  
字(3.4k)|赞(0)|评价(0)|浏览(220)

在本教程中,您将借助示例了解 JavaScript promise 和 promise 链。
    在 JavaScript 中,promise 是处理异步操作的好方法。用于判断异步操作是否成功完成。
    promise 可能有以下三种状态之一。

  • Pending(待处理)
  • Fulfilled(已完成)
  • Rejected(被拒绝)

Promise 以待处理状态开始。这意味着该过程尚未完成。如果操作成功,则该过程以已完成状态结束。并且,如果发生错误,则该过程以被拒绝状态结束。
    例如,当您使用 Promise 向服务器请求数据时,它将处于待处理状态。当数据成功到达时,它将处于已完成状态。如果发生错误,则它将处于拒绝状态。

创建一个 Promise

要创建一个 Promise 对象,我们使用 Promise() 构造函数。

let promise = new Promise(function(resolve, reject){
     //do something
});

Promise() 构造函数将一个函数作为参数。该函数还接收两个函数 resolve() 和 reject() 作为参数。
    如果 promise 成功返回,则调用 resolve() 函数。并且,如果发生错误,则调用 reject() 函数。
    假设下面的程序是一个异步程序。然后可以使用 promise 来处理该程序。

示例 1:带有 Promise 的程序
const count = true;

let countValue = new Promise(function (resolve, reject) {
    if (count) {
        resolve("There is a count value.");
    } else {
        reject("There is no count value");
    }
});

console.log(countValue);

输出

Promise {<resolved>: "There is a count value."}

上面的程序创建了一个 Promise 对象,它具有两个函数:resolve() 和 reject()。如果程序成功,则使用 resolve();如果 promise 中出现错误,则使用 reject()。

JavaScript promise的工作原理

JavaScript Promise 链

当您必须一个接一个地处理多个异步任务时,Promise 很有用。为此,我们使用 promise 链。
    当 promise 被解析后,您可以使用 then(),catch() 和 finally() 方法执行某个操作。

JavaScript then() 方法

当 promise 成功实现或解决时,then() 方法与回调一起使用。
    then() 方法的语法是:

promiseObject.then(onFulfilled, onRejected);
示例 2:用 then() 链接 Promise
// returns a promise

let countValue = new Promise(function (resolve, reject) {
  resolve("Promise resolved");
});

// executes when promise is resolved successfully

countValue
  .then(function successValue(result) {
    console.log(result);
  })

  .then(function successValue1() {
    console.log("You can call multiple functions this way.");
  });

输出

Promise resolved
You can call multiple functions this way.

在上述程序中,then() 方法用于将函数链接到 Promise。当 promise 成功解析时调用 then() 方法。
    你可以用 Promise 链接多个 then() 方法。

JavaScript catch() 方法

当 promise 被拒绝或发生错误时,catch() 方法与回调一起使用。例如,

// returns a promise
let countValue = new Promise(function (resolve, reject) {
   reject('Promise rejected'); 
});

// executes when promise is resolved successfully
countValue.then(
    function successValue(result) {
        console.log(result);
    },
 )

// executes if there is an error
.catch(
    function errorValue(result) {
        console.log(result);
    }
);

输出

Promise rejected

在上面的程序中,promise 被拒绝了。该catch()方法与处理错误的 promise 一起使用。

JavaScript promise 链的工作原理

JavaScript Promise VS 回调

Promise 在某种意义上类似于回调函数,它们都可以用来处理异步任务。
    JavaScript 回调函数也可用于执行同步任务。
    它们的区别可以概括为以下几点:

JavaScript Promise
  1. 语法易于使用且易于阅读。
  2. 错误处理更易于管理。
  3. 例子:
api().then(function(result) {
    return api2() ;
}).then(function(result2) {
    return api3();
}).then(function(result3) {
    // do work
}).catch(function(error) {
    //handle any error that may occur before this point 
});
JavaScript 回调
  1. 语法很难理解。
  2. 错误处理可能难以管理。
  3. 示例:
api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
            if(error) {
                // do something
            }
            else {
                // do something
            }
        });
    });
});
JavaScript finally() 方法

还可以使用 finally() 方法进行 promise。当 promise 被成功解析或拒绝时,finally() 方法将被执行。例如,

// returns a promise
let countValue = new Promise(function (resolve, reject) {
    // could be resolved or rejected   
    resolve('Promise resolved'); 
});

// add other blocks of code
countValue.finally(
    function greet() {
        console.log('This code is executed.');
    }
);

输出

This code is executed.
JavaScript Promise 方法

Promise 对象有多种可用的方法。

方法描述
all(iterable)等待所有 Promise 被解析或任何一个被拒绝
allSettled(iterable)等待所有的 Promise 都被解决或被拒绝
any(iterable)一旦任何一个 Promise 执行完成,就返回 Promise 值
race(iterable)等到任何承诺被解析或拒绝
reject(reason)返回因给定原因被拒绝的新 Promise 对象
resolve(value)返回使用给定值解析的新 Promise 对象
catch()追加拒绝处理程序回调
then()追加已解析的处理程序回调
finally()在 promise 后附加一个处理程序

要详细了解 Promise,请访问使用 Promise

上一教程 :JS CallBack                                          下一教程 :JS async/await

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/promise

相关文章