Promise的链式调用三种写法:
new Promise((resolve, reject) => {
setTimeout(() => {
console.log("请求结果:", 1);
resolve(1);
}, 1000)
}).then(data => {
console.log("第一次对结果处理");
return new Promise((resolve, reject) => {
resolve(data * 2);
});
}).then(data => {
console.log("第二次对结果处理");
return new Promise((resolve, reject) => {
resolve(data * 3);
});
}).then(data => {
console.log("第三次对结果处理");
data *= 4;
console.log("Promise的链式调用结束,最终结果:", data);
}).catch(err => {
console.log("链式调用中某个环节出现错误!!", err);
})
new Promise((resolve, reject) => {
setTimeout(() => {
console.log("请求结果:", 1);
resolve(1);
}, 1000)
}).then(data => {
console.log("第一次对结果处理");
return Promise.resolve(data * 2);
}).then(data => {
console.log("第二次对结果处理");
return Promise.resolve(data * 3);
}).then(data => {
console.log("第三次对结果处理");
data *= 4;
console.log("Promise的链式调用结束,最终结果:", data);
}).catch(err => {
console.log("链式调用中某个环节出现错误!!", err);
})
new Promise((resolve, reject) => {
setTimeout(() => {
console.log("请求结果:", 1);
resolve(1);
}, 1000)
}).then(data => {
console.log("第一次对结果处理");
return data * 2
}).then(data => {
console.log("第二次对结果处理");
return data * 3
}).then(data => {
console.log("第三次对结果处理");
data *= 4;
console.log("Promise的链式调用结束,最终结果:", data);
}).catch(err => {
console.log("链式调用中某个环节出现错误!!", err);
})
Promise.all与式调用:
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
message: "第一个请求结果",
num1: 1
})
})
}), new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
message: "第一个请求结果",
num1: 2
})
})
})
]).then(results => {
console.log("与式调用结果数组results:", results);
console.log("对与式调用结果一起处理操作...");
}).catch(err => {
console.log("Promise.all与式调用错误!!", err);
});
@沉木