JS Promise用法

JS Promise用法


Promise概述

promise对象用于异步计算,相比于回调函数,promise对象除了规定的方法都是不可用的,牺牲了一定自由度的同时,可以将复杂的异步处理模式化。

句法

Promise( /* executor */ function(resolve, reject) { ... } );

new一个Promise构造器进行实例化,返回一个promise对象:

var promise = new Promise(function(resolve, reject) {
    // 异步处理
    // 处理结束后、调用resolve 或 reject
});

Promise 状态

一个promise实例有一下几个状态(默认是Promises/A+的描述状态):

  • pending:初始化阶段,没有fulfilled或者是rejected
  • fulfilled:操作成功完成(promise resolve)
  • rejected:操作失败(promise reject)

如果promise处于pending状态,处理promise的处理模块(handler)就会处于排队状态pending状态可以变成fulfilled或者rejected状态,不过fulfilled状态和rejected状态是不可相互转换的。promise从pending状态到fulfilled或者rejected状态,.then处理只会被调用一次,比如:

var promise = new Promise(function(resolve,reject){
var n = 6
if(n<3)
resolve(console.log('yes')); //成功了调用回调函数
else
reject(new Error(console.log('this is an error'))); //失败调用reject并抛出异常
})

var promise = new Promise(function(resolve,reject){
    var i = 2;
    if(i<3)
    resolve(setTimeout("alert('hello')",5000));
    else
    reject(new Error(console.log('no')));
})
promise.then(console.log('ok'));

Promise 链

Promise.prototype.then()和Promise.prototype.then()方法返回promise对象,就成为promise链,如图:

chains

方法

  • Promise.all()

返回promise在迭代声明中是fulfilled还是reject,如果是fulfill,就返回一个数组,值是按照在迭代器中的顺序成功了的promises。如果返回不成功(reject)的promise,返回迭代器中第一个失败对象的原因。这个方法可以使用在有多个promise的情况下。

  • Promise.race()

如有有一个迭代中的promise被fulfilled或者rejected,这个方法立即返回处理值

  • Promise.reject()

返回被reject的原因

  • Promise.resolve()

返回处理成功的promise对象

例子

'use strict';
var promiseCount = 0;

function testPromise() {
    var thisPromiseCount = ++promiseCount;

    var log = document.getElementById('log');
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Started (<small>Sync code started</small>)<br/>');

    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
    var p1 = new Promise(
        // The resolver function is called with the ability to resolve or
        // reject the promise
        function(resolve, reject) {
            log.insertAdjacentHTML('beforeend', thisPromiseCount +
                ') Promise started (<small>Async code started</small>)<br/>');
            // This is only an example to create asynchronism
            window.setTimeout(
                function() {
                    // We fulfill the promise !
                    resolve(thisPromiseCount);
                }, Math.random() * 2000 + 1000);
        }
    );

    // We define what to do when the promise is resolved/fulfilled with the then() call,
    // and the catch() method defines what to do if the promise is rejected.
    p1.then(
        // Log the fulfillment value
        function(val) {
            log.insertAdjacentHTML('beforeend', val +
                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
        })
    .catch(
        // Log the rejection reason
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');
        });

    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Promise made (<small>Sync code terminated</small>)<br/>');
}

浏览器兼容

FeatureChromeEdgeFirefoxInternetExplorerOperaSafariServo
Promise32.0(Yes)29.0No support197.1No support

本文参考

MDN :
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

JS Promise迷你书:
http://www.kancloud.cn/kancloud/promises-book/44251

JavaScript中的Promise是一种用于处理异步操作的对象。它提供了一种更优雅和可读性更高的方式来编写和处理异步代码。 下面是Promise的基本用法: 1. 创建一个Promise对象: ```javascript const promise = new Promise((resolve, reject) => { // 异步操作的代码 }); ``` 2. 异步操作完成时调用resolve: ```javascript resolve(value); ``` 3. 异步操作失败时调用reject: ```javascript reject(error); ``` 4. 使用Promise的then方法处理成功的结果: ```javascript promise.then((result) => { // 处理成功的结果 }); ``` 5. 使用Promise的catch方法处理错误: ```javascript promise.catch((error) => { // 处理错误 }); ``` 6. 可以使用Promise的finally方法在Promise结束后执行一些操作: ```javascript promise.finally(() => { // 执行一些清理操作 }); ``` 下面是一个示例,演示如何使用Promise执行异步操作: ```javascript function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { const data = 'Some data'; // 模拟异步操作成功,调用resolve并传递数据 resolve(data); // 模拟异步操作失败,调用reject并传递错误信息 // reject('Error occurred'); }, 2000); }); } const promise = fetchData(); promise .then((data) => { console.log('Success:', data); }) .catch((error) => { console.log('Error:', error); }) .finally(() => { console.log('Cleanup'); }); ``` 在上面的示例中,我们创建了一个fetchData函数,它返回一个Promise对象。在Promise的构造函数中,我们模拟了一个异步操作(在这里使用了setTimeout),并根据操作的结果调用resolve或reject。 然后,我们通过调用then方法来处理成功的结果,并通过catch方法来处理错误。最后,我们使用finally方法来执行一些清理操作(无论Promise是成功还是失败)。 这就是Promise的基本用法。使用Promise可以更好地处理异步操作,避免了回调地狱,并提供了更清晰和可读性更高的代码结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值