ale*_*bro 4 javascript promise q
什么是序列化一堆承诺函数调用最方便的方法?
var promised_functions = [
fn1, // call this
fn2, // if previous resolved call this
fn3 // if previous resolved call this
];
q.serialize_functions(promised_functions)
.then(function(){
// if all promises resolved do some
})
Run Code Online (Sandbox Code Playgroud)
您可以在文档中找到解决方案:
promised_functions.reduce(Q.when, Q()).then(function () {
// if all promises resolved do some
});
Run Code Online (Sandbox Code Playgroud)
跳到文档的"序列"部分.要逐字复制:
如果您有许多需要按顺序运行的承诺生成函数,您当然可以手动执行:
return foo(initialVal).then(bar).then(baz).then(qux);
Run Code Online (Sandbox Code Playgroud)
但是,如果要运行动态构造的函数序列,则需要以下内容:
var funcs = [foo, bar, baz, qux];
var result = Q(initialVal);
funcs.forEach(function (f) {
result = result.then(f);
});
return result;
Run Code Online (Sandbox Code Playgroud)
使用reduce可以使这个更紧凑:
return funcs.reduce(function (soFar, f) {
return soFar.then(f);
}, Q(initialVal));
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用超紧凑版本:
return funcs.reduce(Q.when, Q());
Run Code Online (Sandbox Code Playgroud)
你有它.直接从马的嘴里.
| 归档时间: |
|
| 查看次数: |
5360 次 |
| 最近记录: |