回顾承诺,我想知道为什么使用下面的代码,.then/catch调用在.then(onF, onR)之后完成。catch调用是否被放置在队列堆栈的底部?我已经理解了调用堆栈和消息队列(队列堆栈)之间的区别,以及在消息队列开始处理之前清空调用堆栈的事实。
function capitalize(text) {
return text[0].toUpperCase() + text.substr(1);
}
console.log(capitalize("hello"));
function capitalize2(text) {
return new Promise(function (resolve, reject) {
const result = text[0].toUpperCase() + text.substr(1);
return resolve(result);
});
}
capitalize2("hola").then((result) => console.log(result));
const pendingPromise = capitalize2("hola2").then((result) => result); // does nothing
// Adding reject
function capitalize3(text) {
return new Promise(function (resolve, reject) {
if (typeof text !== "string") {
return reject("Argument wrong type");
}
const result = text[0].toUpperCase() + text.substr(1);
return resolve(result);
});
}
capitalize3("bye").then((result) => console.log(result));
capitalize3(1111).then((value) => {console.log(value);}, (reason) => {console.log('1111 ' + reason);});
capitalize3(2222).then((result) => console.log(result)).catch((error) => console.error('2222 ' + error));
function capitalize4(text) {
return new Promise(function (resolve, reject) {
if (typeof text !== "string") {
return reject(new Error("Argument wrong type"));
}
const result = text[0].toUpperCase() + text.substr(1);
return resolve(result);
});
}
capitalize4('hmmm').then((result) => console.log(result));
capitalize4(3333).then((value) => {console.log(value);}, (reason) => {console.error('3333 ' + reason);});
// with error object.
capitalize4(4444).then((result) => console.log(result)).catch((error) => console.error('4444 ' + error.message));
// witch catch
capitalize4(5555).then((value) => {console.log(value);}, (reason) => {console.error('5555 ' + reason);});
node.js中的输出
Hello
Hola
Bye
1111 Argument wrong type
Hmmm
3333 Error: Argument wrong type
5555 Error: Argument wrong type
2222 Argument wrong type
4444 Argument wrong type
我将大写的函数调用按预期完成的顺序排列,即使它们是异步调用。
Promise.then(onFulfilled, onRejected)
表示等待Promise
。如果失败,调用onRejected
Promise.then(onFulfilled).catch(errorFunc)
表示先等待Promise
,再等待onFulfilled
。如果失败,调用onRejected