Promise.all不等待Promise解决

当我向服务器发出请求时,数据将作为承诺(如预期的那样)返回,其中包含正确的数据,但是由于某些原因,程序无法正确执行。

此外,在我将其上载到Zeit之前,该程序是可行的。

获取请求:

1)我知道我不需要'content-type':'application / json'。删除它不会影响程序。

2)这是一个GET请求,端点正常工作。另外,当我在Postman中执行相同的确切请求时,也会得到正确的结果。

// CODE ABOVE DOES NOT MATTER
       .then( ([hours,employees,dayLabor]) => {
           // hours,and dayLabor are empty lists for this exercise '[]'

            let business = fetch(`${config.URL}/${TokenService.getId()}`,{
                headers: {
                    'content-type': 'application/json','table':'business','Authorization':`bearer ${TokenService.getauthToken()}`
                }
            })
            .then(data => {
              console.log('business: ',data,' or ',data.json());
              if (!data.ok){
                  return data.json().then(e => Promise.reject(e));}

              return data.json();
            });


            return Promise.all([business,hours,dayLabor]);
      })
      .then( ([business,dayLabor]) => {  
            // THIS is never executed?

            console.log('completed');            

            //fetch has been completed and the state has been updated so set "fetched" to true

            this.setState({business,'dayLabor': dayLabor.length>0? this.sort(dayLabor):[],fetched: true});


      })
      .catch(error => {
            console.error({error});
      });

输出结果(出于隐私原因将网址括起来):

business:  
Response {type: "cors",url: "https://xxxxxx.herokuapp.com/1",redirected: false,status: 200,ok: true,…}
type: "cors"
url: "https://xxxxxxxx.herokuapp.com/1"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
__proto__: Response
  or  
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(1)
0: {id: 1,business_name: "Fake Company Inc"}
length: 1
__proto__: Array(0)

我想访问“ [[PromiseValue]]”中的对象。我对为什么它不起作用感到困惑,尤其是因为当我在本地运行它时它确实起作用了?看来问题出在“业务”变量或“ Promise.all”不在等待承诺解决。

任何帮助将不胜感激,我一直在搜索,找不到任何解决方案。

lingwoniu 回答:Promise.all不等待Promise解决

一个特殊的问题是您只能拨打一次data.json()。它读取http响应的其余部分(正文),然后对其进行解析)。一旦读取,就无法再次读取。因此,当您这样做时:

console.log(...,data.json())

您正在指示响应对象读取响应主体并返回一个承诺,该承诺将在完成时告诉您。然后,您记录尚未兑现的承诺。而且,然后您将那个承诺丢在了地板上,再也没有做任何事情。

然后,在您的代码后面,您要做

return data.json();

但是,没有更多的响应正文,它已经被读取。您不能多次拨打此电话。所以,这行不通。

因此,要解决的第一件事是从data.json()中删除console.log()并让

return data.json();

读取正文并解析一次响应。

因此,请更改为此:

   // CODE ABOVE DOES NOT MATTER
   .then( ([hours,employees,dayLabor]) => {
       // hours,and dayLabor are empty lists for this exercise '[]'

        let business = fetch(`${config.URL}/${TokenService.getId()}`,{
            headers: {
                'content-type': 'application/json','table':'business','Authorization':`bearer ${TokenService.getAuthToken()}`
            }
        }).then(data => {
          console.log('business: ',data);
          if (!data.ok){
              return data.json().then(e => Promise.reject(e));}

          return data.json();
        });


        return Promise.all([business,hours,dayLabor]);
  }).then( ([business,dayLabor]) => {  
        // THIS is never executed?

        console.log('completed');            

        //fetch has been completed and the state has been updated so set "fetched" to true

        this.setState({business,'dayLabor': dayLabor.length>0? this.sort(dayLabor):[],fetched: true});


  }).catch(error => {
        console.error({error});
  });
本文链接:https://www.f2er.com/2667376.html

大家都在问