[英]My function is not called when i resolve a promise
我的函數resident()從API返回一個數組,函數getTatooineResidents()應該創建一個新的promise,當promise被解析時執行resident()
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()時,它不會執行函數resident()而是返回函數體,當我解析promise時,括號不應該調用函數嗎?
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
}
您正在將res.body.residents
寫入控制台而不對其執行任何操作。
你回來的是const residents
本身的功能。 這就是它返回函數體的原因
相反,您希望從承諾中返回實際的響應數據。
const residents= () => {
let responseResidents = superagent.get('https://swapi.co/api/planets/1/')
.then(res => res.body.residents)
.catch(err => console.log(err))
return responseResidents
}
residents
沒有返回Promise,你需要刪除所有代碼后包括.then
return superagent.get('https://swapi.co/api/planets/1/')
現在你可以調用getTatooineResidents()
並在它之后再應用一個額外的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.