在以下代码中,为什么最后一个axios.get( url.toString())
不返回承诺而是返回未定义?我们该如何处理?
function getCommentersEmailIds( username ) {
let foundUserId = undefined;
//first get user id of username
axios.get( 'https://jsonplaceholder.typicode.com/users?username='+username )
.then(function( response ) {
var foundUser = response.data.find(u=>u.username === username);
return foundUser.id;
})
.then(function( userId ) {
let url = 'https://jsonplaceholder.typicode.com/users/'+ userId.toString() +'/posts';
return axios.get( url.toString());
})
.then(function( posts ) {
//get id of the first post
let postId = posts.data[0].id;
let url = 'https://jsonplaceholder.typicode.com/comments?' + postId.toString();
return axios.get( url.toString());
})
.catch(function( error ) {
console.log( error.message );
});
}
var promiseForComments = getCommentersEmailIds('Bret');
promiseForComments.then(function( comments ) {
comments.data.array.forEach(comment => {
console.log(comment.email);
});
})
.catch(function( error ) {
console.log( error.message );
});
答案 0 :(得分:4)
这里的问题是,您缺少return
中的getCommentersEmailIds()
语句,而不是第二个对axios.get
的调用所特有的问题:
function getCommentersEmailIds( username ) {
let foundUserId = undefined;
//Update: add return before axio.get
return axios.get( 'https://jsonplaceholder.typicode.com/users?username='+username )
.then(function( response ) {
var foundUser = response.data.find(u=>u.username === username);
return foundUser.id;
})
.then(function( userId ) {
let url = 'https://jsonplaceholder.typicode.com/users/'+ userId.toString() +'/posts';
return axios.get( url.toString());
})
.then(function( posts ) {
//get id of the first post
let postId = posts.data[0].id;
let url = 'https://jsonplaceholder.typicode.com/comments?' + postId.toString();
return axios.get( url.toString());
})
.catch(function( error ) {
console.log( error.message );
});
}
通过从axios.get()
返回getCommentersEmailIds()
的承诺,随后的链接(导致forEach()
上的comments.data.array
迭代)应按预期执行。
希望有帮助!
答案 1 :(得分:1)
您没有从getCommentersEmailIds函数返回任何内容
做到
/usr/include/uuid/uuid.h
}