Angular - 将函数转换为 Promise
Angular - convert a function into a promise
考虑以下伪代码:
// main
function1();
function2();
...
//the rest of the code
....
// function1:
someservice.getPhone().then(calback1);
// function2:
someservice.getAddress().then(calback2);
我该怎么做才能确保在 function1 和 function2 都通过它们的回调之前不执行其余代码?
谢谢
承诺的 .then
方法总是 returns 派生的承诺。使用那些派生的承诺来延迟后续功能的执行。
// function1:
var derivedPromise1 = service.getPhone().then(calback1);
// function2:
var derivedPromise2 = someservice.getAddress().then(calback2);
$q.all([derivedPromise1, derivedPromise2])
.then(function onFulfilled(resultArray) {
//code placed here
}).catch(function onRejected(errorResult) {
//error handling code here
});
$q
服务将等待 callback1
和 callback2
成功完成,然后再调用 onFulfilled
函数中的代码。否则,$q
服务将为第一个被拒绝的承诺调用 onRejected
函数。
考虑以下伪代码:
// main
function1();
function2();
...
//the rest of the code
....
// function1:
someservice.getPhone().then(calback1);
// function2:
someservice.getAddress().then(calback2);
我该怎么做才能确保在 function1 和 function2 都通过它们的回调之前不执行其余代码?
谢谢
承诺的 .then
方法总是 returns 派生的承诺。使用那些派生的承诺来延迟后续功能的执行。
// function1:
var derivedPromise1 = service.getPhone().then(calback1);
// function2:
var derivedPromise2 = someservice.getAddress().then(calback2);
$q.all([derivedPromise1, derivedPromise2])
.then(function onFulfilled(resultArray) {
//code placed here
}).catch(function onRejected(errorResult) {
//error handling code here
});
$q
服务将等待 callback1
和 callback2
成功完成,然后再调用 onFulfilled
函数中的代码。否则,$q
服务将为第一个被拒绝的承诺调用 onRejected
函数。