[英]Is it valid to resolve promise in the promise constructor?
Is it valid to resolve the promise in the constructor like this 像这样在构造函数中解析promise是否有效
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
instead of the resolving after the construction creation like the following 而不是像下面这样在构造创建后进行解析
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
Yes, it is perfectly acceptable to resolve a new Promise synchronously in the constructor. 是的,在构造函数中同步解决新的Promise是完全可以接受的。 IIRC, it is even a test case in the A+ promise validation suite. IIRC,它甚至是A + promise验证套件中的测试用例。
However if the resolution is not conditional, it is more clearly achieved using the ES6 Promise static method `resolve': 但是,如果解决方案不是有条件的,则可以使用ES6 Promise静态方法“ resolve”更清楚地实现:
var promise1 = Promise.resolve( 'foo');
Note the two approaches differ if errors are thrown: 请注意 ,如果抛出错误,则两种方法会有所不同:
new Promise( executor)
returns a rejected promise. 如果执行程序抛出错误,则new Promise( executor)
将返回被拒绝的承诺。 Promise.resolve
throws an error, the exception prevents a call to Promise.resolve
taking place. 如果对Promise.resolve
的参数求Promise.resolve
抛出错误,则异常会阻止对Promise.resolve
的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.