【问题标题】:Response not ready in .then().then() 中的响应未准备好
【发布时间】:2020-05-05 06:40:20
【问题描述】:

我有一个函数返回一个最终返回一个数组的承诺。在我的 .then 中,当我尝试访问数组中的第一个项目时,它仍然是未定义的。当我记录响应是正确的但如果我访问它里面的项目失败。

myPromise().then((response)=>{
  ///consoles array
  console.log(response);
  //undefined
  console.log(response[0]);
  //consoles the item
  setTimeout(function(){console.log(response[0])}, 1000);
}

baseCall( url ){
  return new Promise((resolve, reject)=>{
     request(url , (error, response, json) => {
        if (!error && response.statusCode === 200) {
          resolve(JSON.parse(json));  
             } else {
                reject("Error: Something wrong");
             }
      });
   });
}

myPromise(){
   let myReturn = [];
   baseCall( 'sampleurl' ).then((response)=>{
      response['valueNeed'].forEach(value =>{
          let addValue = {};
          addValue["someItem'] = value.someItem;
          //.... add more stuff
          myReturn.push(addValue);
      }
   }).then(()=>{
      resole(myReturn);
   });
}

Json 被解析

{
  "valueNeed":[
     {"id": 1, "someItem": "someVal1"},
     {"id": 2, "someItem": "someVal2"}
   ]
}

如何让它在没有超时的情况下工作?我认为 .then 方法在承诺解决之前不会触发。

【问题讨论】:

  • 你使用的是 'fetch' API 还是 axios ?
  • @Sohail 我现在正在使用请求。

标签: javascript arrays promise


【解决方案1】:

response 将是 HTTP 响应对象,而不是您的数组。你可以试试response.body。或者,像回调方法一样,body 可以作为第二个参数传递,即

request().then((res, body) => { console.log(body) })

【讨论】:

  • 我应该澄清一下。我不返回响应。我正在从方法中的 response.body 创建一个数组,并返回包含所有返回对象的数组。我将更新我的问题以显示。
  • @levif1 您需要展示一个正在解析的 JSON 的示例,这个问题看起来更像与 request 无关,而与您如何索引它有关
  • 当我使用 console.log() 时,我在 myPromise() 中返回的数组就在那里。我只是不知道为什么当我尝试访问数组中的一个项目时它说它未定义,但是如果我 setTimeout 和控制台日志它可以工作。 @詹姆斯
  • @levif1 你的代码有错别字,只是排除了吗?即respone['valueNeed'] 应该是response["valueNeed"]
  • 谢谢。那只是我的代码的一个例子。我只是在写的时候打错了。
【解决方案2】:

尝试将 response 分配给另一个变量,例如 const tempvariable = response,然后使用该临时变量访问数组,有时 react 会清理内存并且可能会发生类似的奇怪事情。

【讨论】:

  • 你没有在你的 myPromise() 方法中返回任何东西,我没有看到你最后从哪里得到解析回调然后你应该在 myPromise() 中返回一个新的承诺方法,然后使用 Promise 构造函数 return new Promise((resolve, reject) => { baseCall('url').then(res => { ... }).then(() => resolve(myReturn)) }) 提供的解析回调解决该方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
相关资源
最近更新 更多