我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then()
.最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise
构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
假设我有一组承诺正在发出网络请求,其中一个会失败:
// http://does-not-exist will throw a TypeError
var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]
Promise.all(arr)
.then(res => console.log('success', res))
.catch(err => console.log('error', err)) // This is executed
Run Code Online (Sandbox Code Playgroud)
让我们说我想等到所有这些都结束了,不管一个人是否失败了.对于我可以没有的资源,可能存在网络错误,但如果我可以获得,我希望在继续之前.我想优雅地处理网络故障.
既然Promise
没有留下任何空间,那么在不使用promises库的情况下,处理此问题的推荐模式是什么?
无论是ES6 Promise还是蓝鸟Promise,Q Promise等.
如何测试以查看给定对象是否为Promise?
我一直在使用ES6 Promise.
通常,Promise是这样构造和使用的
new Promise(function(resolve, reject){
if (someCondition){
resolve();
} else {
reject();
}
});
Run Code Online (Sandbox Code Playgroud)
但我一直在做类似下面的事情,为了灵活性而采取外面的决心.
var outsideResolve;
var outsideReject;
new Promise(function(resolve, reject) {
outsideResolve = resolve;
outsideReject = reject;
});
Run Code Online (Sandbox Code Playgroud)
然后
onClick = function(){
outsideResolve();
}
Run Code Online (Sandbox Code Playgroud)
这很好,但是有更简单的方法吗?如果没有,这是一个好习惯吗?
如何拒绝async/await函数返回的promise?
例如,最初
foo(id: string): Promise<A> {
return new Promise((resolve, reject) => {
someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400))
});
}
Run Code Online (Sandbox Code Playgroud)
转换为async/await
async foo(id: string): Promise<A> {
try{
await someAsyncPromise();
return 200;
} catch(error) {//here goes if someAsyncPromise() rejected}
return 400; //this will result in a resolved promise.
});
}
Run Code Online (Sandbox Code Playgroud)
那么,在这种情况下,我怎么能正确地拒绝这个承诺呢?
javascript asynchronous typescript es6-promise ecmascript-2017
假设我有以下代码.
function divide(numerator, denominator) {
return new Promise((resolve, reject) => {
if(denominator === 0){
reject("Cannot divide by 0");
return; //superfluous?
}
resolve(numerator / denominator);
});
}
Run Code Online (Sandbox Code Playgroud)
如果我的目的是reject
尽早退出,那么我是否应该return
立即养成习惯?
我有一个Promise数组,我正在使用Promise.all(arrayOfPromises)解析;
我接着继续承诺链.看起来像这样
existingPromiseChain = existingPromiseChain.then(function() {
var arrayOfPromises = state.routes.map(function(route){
return route.handler.promiseHandler();
});
return Promise.all(arrayOfPromises)
});
existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
// do stuff with my array of resolved promises, eventually ending with a res.send();
});
Run Code Online (Sandbox Code Playgroud)
我想添加一个catch语句来处理单个promise,以防它出错.但是当我尝试时,Promise.all返回它找到的第一个错误(忽略其余的),然后我无法从其余的数据中获取数据数组中的promise(没有错误).
我尝试过像......
existingPromiseChain = existingPromiseChain.then(function() {
var arrayOfPromises = state.routes.map(function(route){
return route.handler.promiseHandler()
.then(function(data) {
return data;
})
.catch(function(err) {
return err
});
});
return Promise.all(arrayOfPromises)
});
existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
// do stuff with my array of resolved promises, eventually ending with a res.send();
}); …
Run Code Online (Sandbox Code Playgroud) 看看MDN,看起来values
传递给then()
Promise.all 的回调包含了promises顺序的值.例如:
var somePromises = [1, 2, 3, 4, 5].map(Promise.resolve);
return Promise.all(somePromises).then(function(results) {
console.log(results) // is [1, 2, 3, 4, 5] the guaranteed result?
});
Run Code Online (Sandbox Code Playgroud)
任何人都可以引用规范说明values
应该在哪个顺序?
PS:运行这样的代码表明这似乎是真的,虽然这当然没有证据 - 它可能是巧合.
为了学习Angular 2,我正在尝试他们的教程.
我收到这样的错误:
(node:4796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r ejection id: 1): Error: spawn cmd ENOENT
[1] (node:4796) DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.
js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud)
我在SO中经历了不同的问题和答案,但无法找出"未处理的承诺拒绝"是什么.
任何人都可以简单地解释一下它是什么Error: spawn cmd ENOENT
,也是什么,当它出现时,我必须检查以摆脱这个警告?
es6-promise ×10
javascript ×10
promise ×8
bluebird ×3
q ×2
angular ×1
asynchronous ×1
scope ×1
spawn ×1
typescript ×1