Angularjs:将 promises 与同步函数混合
Angularjs: Mixing promises with synchronous functions
在 中,我发布了一个关于修复一段涉及 returning promise 的问题,有人向我指出我不必要地创建了 wrapper promises。按照建议,我得到了一个更简洁的代码。我确实有一个后续问题:在像下面这样的情况下(虚构的示例),我需要将承诺代码与非承诺代码混合,我没有看到一个选项,只能使用 $q.defer()
构建我自己的承诺最后 returning d.promise
。有better/recommended的方法吗?可以将我的自定义承诺与 return 他们自己承诺的功能混合使用吗?
function my_func(use_promise) {
var d = $q.defer();
if (!use_promise) {
x = do_a_sync_function_that_takes_time();
d.resolve(x)
return d.promise;
} else {
return do_a_promise_function_that_takes_time()
.then (function(data) {
return (data); // this gets promisified as we are in .then
})
.catch(function (err) {return "Error ";});
}
return d.promise;
}
要将同步值转换为 Promise,只需使用 $q.when
或 $q.resolve
:
function my_func(use_promise) {
̶v̶a̶r̶ ̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
if (!use_promise) {
var x = do_a_sync_function_that_takes_time();
̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶x̶)̶
return $q.when(x);
} else {
return do_a_promise_function_that_takes_time()
.then (function(data) {
return (data); // this gets promisified as we are in .then
})
.catch(function (err) {return "Error ";});
}
̶r̶e̶t̶u̶r̶n̶ ̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶
}
有关详细信息,请参阅
在 $q.defer()
构建我自己的承诺最后 returning d.promise
。有better/recommended的方法吗?可以将我的自定义承诺与 return 他们自己承诺的功能混合使用吗?
function my_func(use_promise) {
var d = $q.defer();
if (!use_promise) {
x = do_a_sync_function_that_takes_time();
d.resolve(x)
return d.promise;
} else {
return do_a_promise_function_that_takes_time()
.then (function(data) {
return (data); // this gets promisified as we are in .then
})
.catch(function (err) {return "Error ";});
}
return d.promise;
}
要将同步值转换为 Promise,只需使用 $q.when
或 $q.resolve
:
function my_func(use_promise) {
̶v̶a̶r̶ ̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
if (!use_promise) {
var x = do_a_sync_function_that_takes_time();
̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶x̶)̶
return $q.when(x);
} else {
return do_a_promise_function_that_takes_time()
.then (function(data) {
return (data); // this gets promisified as we are in .then
})
.catch(function (err) {return "Error ";});
}
̶r̶e̶t̶u̶r̶n̶ ̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶
}
有关详细信息,请参阅