执行函数时获取不可见对象的承诺

时间:2019-06-08 17:40:56

标签: javascript

函数getTatooineResidents()应该从函数residents()返回一个数组,但会在数组的第一个元素之前添加[object Promise]

当我运行residents()时,它确实会返回我想要的数组,但是当我在函数getTatooineResidents()中使用该数组时,它将在第一个元素之前创建对象诺言

const superagent = require('superagent')
function residents(){
    const tattoineResidents = 
superagent.get('https://swapi.co/api/planets/1/')
    .then(res => console.log(res.body.residents))
    .catch(err => console.log(err))
    return tattoineResidents 
}

const getTatooineResidents=()=>{
    const residentsOfTattoine = residents()
    return new Promise((resolve, reject) => {
        if(3 > 2) resolve([residentsOfTattoine])
        reject('I am broken!')
      })
}

在测试中我得到:

+预期:

[

          "https://swapi.co/api/people/1/",
          "https://swapi.co/api/people/2/",
          "https://swapi.co/api/people/4/",
          "https://swapi.co/api/people/6/",
          "https://swapi.co/api/people/7/",
          "https://swapi.co/api/people/8/",
          "https://swapi.co/api/people/9/",
          "https://swapi.co/api/people/11/",
          "https://swapi.co/api/people/43/",
          "https://swapi.co/api/people/62/" 

        ] 

-实际:

[
  -  "[object Promise]"
  +  "https://swapi.co/api/people/1/"
  +  "https://swapi.co/api/people/2/"
  +  "https://swapi.co/api/people/4/"
  +  "https://swapi.co/api/people/6/"
  +  "https://swapi.co/api/people/7/"
  +  "https://swapi.co/api/people/8/"
  +  "https://swapi.co/api/people/9/"
  +  "https://swapi.co/api/people/11/"
  +  "https://swapi.co/api/people/43/"
  +  "https://swapi.co/api/people/62/"
   ]

0 个答案:

没有答案