// 创建一个 Promise 实例
const myPromise = new Promise((resolve, reject) => {
// 模拟异步操作,比如网络请求或定时器
setTimeout(() => {
const success = true; // 假设这里是根据某些条件决定是否成功
if (success) {
resolve('操作成功'); // 如果成功,调用 resolve 并传递结果
} else {
reject('操作失败'); // 如果失败,调用 reject 并传递错误信息
}
}, 1000);
});
// 使用 then 方法处理 Promise 的成功和失败情况
myPromise
.then(result => {
console.log(result); // 输出: 操作成功
})
.catch(error => {
console.error(error); // 输出: 操作失败
});
// 你也可以链式调用多个 then 方法
myPromise
.then(result => {
console.log('第一个 then:', result);
return '这是第二个 then 的输入';
})
.then(input => {
console.log('第二个 then:', input);
})
.catch(error => {
console.error(error);
});
resolve 和 reject。当异步操作成功时调用 resolve,失败时调用 reject。then。希望这段代码和解释对你理解 JavaScript 的 Promise 有帮助!
上一篇:js promise then
下一篇:nodejs promise
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站