我的函数residents()从API返回一个数组,函数getTatooineResidents()应该创建一个新的promise,当该promise被解决时,将执行residents()
const superagent = require('superagent')
const residents=()=>{
superagent.get('https://swapi.co/api/planets/1/')
.then(res =>
console.log(res.body.residents))
.catch(err => console.log(err))
return residents
}
residents()
const getTatooineResidents=()=>{
return new Promise((resolve, reject) => {
if(3 > 2) resolve(residents())//instead of executing residents() it just writes the body of the function
reject('I am broken!')
})
}
当我调用getTatooineResidents()时,它没有执行函数residents(),而是返回函数的主体,当我解决诺言时,括号不应该调用函数吗?
AssertionError [ERR_ASSERTION]:
The function should a return promise which resolves with an array of urls for the residents of Tatooine like :
[array of URLS]
the promise that was returned from you function resolved with: ()=>{
superagent.get('https://swapi.co/api/planets/1/')
.then(res => console.log(res.body.residents))
.catch(err => console.log(err))
return residents
}
答案 0 :(得分:0)
您正在编写res.body.residents
来进行控制台,而不对其进行任何操作。
您要返回的是函数本身const residents
。
那就是为什么它返回函数体
相反,您想从promise中返回实际的响应数据。
const residents= () => {
let responseResidents = superagent.get('https://swapi.co/api/planets/1/')
.then(res => res.body.residents)
.catch(err => console.log(err))
return responseResidents
}
答案 1 :(得分:0)
residents
没有返回Promise,您需要删除.then
之后的所有代码
return superagent.get('https://swapi.co/api/planets/1/')
现在您可以拨打getTatooineResidents()
,然后在其后加上一个额外的内容。