在Promise中使用Promise可以通过以下几种方式实现:
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('First promise resolved');
}, 1000);
})
.then((result) => {
console.log(result);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Second promise resolved');
}, 1000);
});
})
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved');
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 2 resolved');
}, 2000);
});
Promise.all([promise1, promise2])
.then((results) => {
console.log(results[0]); // Output: "Promise 1 resolved"
console.log(results[1]); // Output: "Promise 2 resolved"
})
.catch((error) => {
console.error(error);
});
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved');
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 2 resolved');
}, 2000);
});
Promise.race([promise1, promise2])
.then((result) => {
console.log(result); // Output: "Promise 1 resolved"
})
.catch((error) => {
console.error(error);
});
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云