下面是一个示例代码,展示了如何创建一个新的 Promise,而不是使用 then() 方法:
function add(a, b) {
return new Promise(function(resolve, reject) {
if (typeof a !== 'number' || typeof b !== 'number') {
reject(new Error('Invalid arguments'));
}
setTimeout(function() {
resolve(a + b);
}, 1000);
});
}
function multiply(c, d) {
return new Promise(function(resolve, reject) {
if (typeof c !== 'number' || typeof d !== 'number') {
reject(new Error('Invalid arguments'));
}
setTimeout(function() {
resolve(c * d);
}, 1000);
});
}
add(2, 3)
.then(function(result) {
console.log('Sum:', result);
return multiply(result, 4);
})
.then(function(result) {
console.log('Product:', result);
})
.catch(function(error) {
console.error(error);
});
在上面的代码中,我们创建了两个函数 add()
和 multiply()
,每个函数都返回一个新的 Promise 对象。我们使用这些函数来执行异步操作,并通过 resolve()
方法解析最终的结果。然后,我们使用新创建的 Promise 对象来链式调用不同的操作,而不是使用 then() 方法。
在上述示例中,我们先使用 add()
函数将 2 和 3 相加,然后将结果传递给 multiply()
函数,再将结果乘以 4。最后,我们通过 then()
方法打印出结果。如果任何一个操作失败,我们使用 catch()
方法捕获错误并打印错误信息。