请解释以下实例方法的作用,并举例说明使用方法
Promise.prototype.then
Promise.prototype.done
Promise.prototype.always
Promise.prototype.fail
在下列Promise所提供的方法中,用来向成功或者失败的回调函数队列中添加回调函数的是( )
A. done
B. then
C. always
D. fail
请解释以下实例方法的作用,并举例说明使用方法
Promise.prototype.then
Promise.prototype.done
Promise.prototype.always
Promise.prototype.fail
在下列Promise所提供的方法中,用来向成功或者失败的回调函数队列中添加回调函数的是( )
A. done
B. then
C. always
D. fail
这些文档里都有,我就直接抄文档了,那个选择题,选择B,文档一看都清楚了。
Promise.prototype.then(onFulfilled, onRejected)
该方法用于注册一个回调函数,当Promise对象成功(fulfilled)时,会执行 onFulfilled 回调函数,并传递Promise对象的结果作为参数;当Promise对象失败(rejected)时,会执行 onRejected 回调函数,并传递Promise对象的拒因作为参数。该方法返回一个新的Promise对象,该新Promise对象的状态和结果由回调函数的返回值决定。
例如:
const promise = new Promise((resolve, reject) => {
// 一些异步操作
setTimeout(() => {
const result = 'Success!';
resolve(result);
}, 1000);
});
promise.then((result) => {
console.log(result); // 'Success!'
}).catch((error) => {
console.error(error);
});
Promise.prototype.done(onFulfilled, onRejected)
该方法与 then() 方法类似,但是不返回一个新的Promise对象,也没有捕获错误的机制。相反,它在发生未处理的错误时,将错误直接抛出,使其在全局范围内捕获。
例如:
const promise = new Promise((resolve, reject) => {
// 一些异步操作
setTimeout(() => {
const result = 'Success!';
resolve(result);
}, 1000);
});
promise.done((result) => {
console.log(result); // 'Success!'
}, (error) => {
console.error(error);
});
Promise.prototype.always(onFinally)
该方法注册一个回调函数,该回调函数在Promise对象完成(resolved)时执行,无论Promise对象是成功还是失败。回调函数没有参数,也不会影响Promise对象的状态或结果。该方法返回一个新的Promise对象,该新Promise对象与原Promise对象状态和结果相同。
例如:
const promise = new Promise((resolve, reject) => {
// 一些异步操作
setTimeout(() => {
const result = 'Success!';
resolve(result);
}, 1000);
});
promise.then((result) => {
console.log(result); // 'Success!'
}).catch((error) => {
console.error(error);
}).finally(() => {
console.log('Promise completed.'); // 'Promise completed.'
});
Promise.prototype.fail(onRejected)
该方法与 then() 方法类似,但只注册处理Promise对象失败的回调函数。它返回一个新的Promise对象,该新Promise对象的结果由回调函数的返回值决定。
例如:
const promise = new Promise((resolve, reject) => {
// 一些异步操作
setTimeout(() => {
const error = new Error('Error!');
reject(error);
}, 1000);
});
promise.fail((error) => {
console.error(error.message); // 'Error!'
});