Promise的简单应用

定义函数:

function test() {
    return new Promise((resolve, reject) => {
    	let result = getResult()
        if (result == 1)
            resolve('成功')
        else
            reject('失败')
    })
}

function getResult() {
    return Math.random() > 0.5 ? 1 : 2
}

调用输出:

test().then(res=>console.log(res)).catch(res=>console.log(res))
//getResult()为1打印成功,为2打印失败
### Vue 实现简单Promise 的代码示例 以下是一个基于 Vue 环境实现的简化版 Promise 示例。通过参考提供的引用内容[^1]、[^2]、[^3]、[^4],并结合 Vue 的特性,可以实现一个基础版本的 Promise。 ```javascript // 在 Vue 环境中手写一个简单Promise class VuePromise { constructor(executor) { this.status = 'pending'; // 初始状态为 pending this.value = undefined; // 成功时的值 this.reason = undefined; // 失败时的原因 this.onFulfilledCallbacks = []; // 存储成功回调 this.onRejectedCallbacks = []; // 存储失败回调 const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach((callback) => callback(this.value)); } }; const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach((callback) => callback(this.reason)); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value; onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; }; let promise2 = new VuePromise((resolve, reject) => { if (this.status === 'fulfilled') { setTimeout(() => { try { let x = onFulfilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } if (this.status === 'rejected') { setTimeout(() => { try { let x = onRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } if (this.status === 'pending') { this.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); } }); return promise2; } catch(onRejected) { return this.then(null, onRejected); } } function resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise #<Promise>')); } if (x instanceof VuePromise) { x.then(resolve, reject); return; } resolve(x); } ``` #### 代码说明 1. **构造函数**:`VuePromise` 的构造函数接受一个 `executor` 函数,并初始化 `status`、`value` 和 `reason` 属性。 2. **resolve 和 reject 方法**:分别用于设置 `fulfilled` 和 `rejected` 状态,并触发对应的回调函数[^2]。 3. **then 方法**:支持链式调用,并处理异步操作的结果。 4. **catch 方法**:用于捕获异常。 5. **resolvePromise 函数**:处理 Promise 链式调用中的特殊情况[^4]。 ### Vue 中的应用场景 在 Vue 中,可以通过 `VuePromise` 替代原生 Promise 来管理异步任务。例如: ```javascript new Vue({ el: '#app', data: { result: null, }, mounted() { new VuePromise((resolve, reject) => { setTimeout(() => resolve('Hello VuePromise'), 1000); }) .then((message) => { this.result = message; }) .catch((error) => { console.error(error); }); }, }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值