async getContrat(){
//get the customer
const customer = await this.http.get('./customer.json').toPromise();
//get the contract from url
const contract = await this.http.get(customer.contractUrl).toPromise();
return contract; // you can return what you want here
}
然后叫它:)
this.myService.getContrat().then( (contract) => {
// do what you want
});
let customer;
try {
customer = await this.http.get('./customer.json').toPromise();
}catch(err){
console.log('Something went wrong will trying to get customer');
throw err; // propagate the error
//customer = {}; //it's a possible case
}
82
你也可以链接Promises . 按照这个例子
<html>
<head>
<meta charset="UTF-8">
<title>Chaining Promises</title>
</head>
<body>
<script>
const posts = [
{ title: 'I love JavaScript', author: 'Wes Bos', id: 1 },
{ title: 'CSS!', author: 'Chris Coyier', id: 2 },
{ title: 'Dev tools tricks', author: 'Addy Osmani', id: 3 },
];
const authors = [
{ name: 'Wes Bos', twitter: '@wesbos', bio: 'Canadian Developer' },
{ name: 'Chris Coyier', twitter: '@chriscoyier', bio: 'CSS Tricks and Codepen' },
{ name: 'Addy Osmani', twitter: '@addyosmani', bio: 'Googler'},
];
function getPostById(id) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/HTTP request
setTimeout(() => {
// find the post we want
const post = posts.find(post => post.id == id);
if (post) {
resolve(post) // send the post back
} else {
reject(Error('No Post Was Found!'));
}
},200);
});
}
function hydrateAuthor(post) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/http request
setTimeout(() => {
// find the author
const authorDetails = authors.find(person => person.name === post.author);
if (authorDetails) {
// "hydrate" the post object with the author object
post.author = authorDetails;
resolve(post);
} else {
reject(Error('Can not find the author'));
}
},200);
});
}
getPostById(4)
.then(post => {
return hydrateAuthor(post);
})
.then(post => {
console.log(post);
})
.catch(err => {
console.error(err);
});
</script>
</body>
</html>
3 回答
您可以使用
mergeMap
运算符执行此操作首先导入运算符如下:
import 'rxjs/add/operator/mergeMap';
那么这是你如何链接两个电话:
这里有更多细节:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
有关mergeMap运算符的更多信息,请参见here
使用rxjs来完成这项工作是一个非常好的解决方案 . 它易于阅读吗?我不知道 .
另一种方法是使用 await/async 来实现这一目标并且更具可读性(在我看来) .
示例:
然后叫它:)
或者在异步功能中
您还可以使用 try/catch 来管理错误:
你也可以链接Promises . 按照这个例子