【发布时间】:2020-04-27 18:09:27
【问题描述】:
我的问题 ID 与 Javascript 承诺相关。 Promise 构造函数允许我们编写解析或拒绝的逻辑。例如
let x = true;
const promise1 = new Promise(function(resolve, reject) {
if (x == true){ // Reject - Resolve logic
resolve('Success!');
}
else {
reject('Reject');
}
});
但是现在如果我用 .then ( () => console.log('Hello')) 链接它,如果没有提供逻辑,它如何被接受或拒绝?
promise1.then(() => console.log('Hello') , undefined)
.then(undefined , () => console.log('World'))
.catch( () => console.log('Error'));
我的问题是:
1. new Promise 被接受或拒绝,然后调用 .then()'s onFullilled 或 onRejected。此外,.then() 返回一个新的 Promise。那么.then()返回的promise中承诺了什么?
2。我在哪里提供解决或拒绝.then() 返回的承诺的逻辑? (就像我在上面的构造函数中所做的那样)
另外,据我所知 - JS 中已经存在 resolve 和 reject 函数,它们会改变 Promise 状态
谢谢
【问题讨论】:
-
您的意思是在您的
if (x == true)中省略else,这意味着当x 为真时它将同时解析和拒绝? -
@Wyck 错字。固定。
-
@Wyck 无法拒绝已解决的承诺。
console.assert(true === await new Promise((resolve, reject) => { resolve(true); reject(false)})) -
@BlueWater86 解决后不拒绝的好风格:见stackoverflow.com/questions/32536049/…它是一个错字。请参阅 lynxx 的评论。
-
同意。只是想指出一个承诺不能同时被解决和拒绝。
标签: javascript node.js promise