hum*_*ace 2 javascript terminology promise
因为我遇到了构造:
var variable = Promise.resolve().then(function(){
//
// do usefull stuff
//
return result;
});
Run Code Online (Sandbox Code Playgroud)
经常,因为它似乎有一些相似但不同的用途:
var variable = Promise.resolve((function(){
//
// do usefull stuff
//
return result;
})());
Run Code Online (Sandbox Code Playgroud)
并且主要是因为我似乎已经经常使用它,就像Promise-chain开始的那样,是这个更明确的长手代码的简称:
var variable = new Promise((resolve) => {
resolve(()=>{
//
// do usefull stuff
//
return result;
});
});
Run Code Online (Sandbox Code Playgroud)
我非常乐意知道其他人如何提及它?它被称为Promise-Chain-Head,或者可能是Function-To-Promise-Chain-Integrator,还是有名字?
我考虑过/知道这个结构的名称,有助于将它的差异传达给纯粹的"转换参数承诺" Promise.resolve()
构造的第二个版本吗?
奖励:关于两个初始结构的区别,我假设主要是第二个版本不会像第一个Promise-Chain-Head那样处理统一的"转换为承诺拒绝"时的任何错误/异常.
没有直接的名称,Promise.resolve().then
但这种模式通常用Promise.try
.
Promise.try
我们在bluebird上仍然是第1阶段的JavaScript提议(意味着它尚未在浏览器中采用或实现).
您可以使用以下方式对其进行填充:
if (typeof Promise.try !== 'function') {
Promise.try = {
try(func) {
if (typeof this !== 'function') {
throw new TypeError('Receiver must be a constructor');
}
return new this(function (resolve) {
resolve(func());
});
}
}.try;
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
Promise.try(() => {
// same as Promise.resolve().then(...
});
Run Code Online (Sandbox Code Playgroud)
或者您可以使用异步功能:
(async () => { // errors here are converted to rejections
})();
Run Code Online (Sandbox Code Playgroud)
由于异步/等待变得流行,因此异步函数会自动将抛出的错误转换为拒绝,因此通常不会成为问题.