fetch API不会在promise.all中返回值

时间:2018-02-14 02:56:34

标签: javascript typescript promise xmlhttprequest fetch

我将一个api调用从XMLHttpRequest更改为fetch和promise.all我在代码中停止了工作。非常感谢任何帮助。谢谢

以下是使用XMLHttpRequest的原始api调用以及来自此调用和另一个api调用的promise.all:

const configApiPromise = token => {
  return new Promise(function (resolve, reject) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "/api/econfig", true);
    xhttp.setRequestHeader("Authorization", `Bearer ${token}`);
    xhttp.onload = function () {
      if (this.status >= 200 && this.status < 300 && this.readyState == 4) {
        resolve(JSON.parse(xhttp.response));
      } else {
        reject({
          status: this.status,
          statusText: xhttp.statusText
        });
      }
    };
    xhttp.onerror = function () {
      reject({
        status: this.status,
        statusText: xhttp.statusText
      });
    };
    xhttp.send();
  });
}

Promise.all([configApiPromise(token), simApiPromise(token)]);

这是我用fetch编写的api调用,以及另一个api调用的promise.all:

const configApiFetch = token => {
  var authHeader = new Headers();
  authHeader.append('Authorization', `Bearer ${token}`);

  var myInit = {
    method: 'GET',
    headers: authHeader,
    mode: 'cors',
    cache: 'default'
  };

  var myRequest = new Request('/api/econfig', myInit);

  return fetch(myRequest)
    .then(checkStatus)
    .then(parseJSON)
    .then(function (data) {
      return data; // here in debugger I see it returns data but in promise.all it returns undefined
    });
}

Promise.all([configApiFetch(token), simApiPromise(token)]);

第一个代码工作正常,值从promise返回,而第二个(fetch调用),promise.all()之后的值是未定义的,尽管在检查configApiFetch时它返回数据。哪个部分我做错了?谢谢你的帮助

这里也使用了两个函数:

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json();
}

以下是调用promise.all的完整代码:

window.accessToken = new Promise((resolve, reject) => {
                   //do some stuff here
                     resolve(token)
                }
            });
       }).then(token => {
           Promise.all([configApiPromise(token), simApiPromise(token)]);

在另一个地方我正在等待这个承诺的结果,它返回未定义的fetch api调用:

const response = await (window as any).accessToken; // whole response is undefinded
const configresponse = JSON.parse(response[0]); 
const simResponse = JSON.parse(response[1]); 

2 个答案:

答案 0 :(得分:1)

是的,你错过了return

window.accessToken = new Promise((resolve, reject) => {
    //do some stuff here {
       resolve(token)
    // }
}).then(token => {
    return Promise.all([configApiPromise(token), simApiPromise(token)]);
//  ^^^^^^
});

你的configApiPromise函数的实现方式无关紧要。

答案 1 :(得分:1)

这种请调试我的代码问题很难回答,尤其是当您在实际代码中没有遗漏的问题中遗漏return语句时。

也许你正在搞乱名为accessToken的全球价值,你可以确定它的设定:

window.accessToken = new Promise((resolve, reject) => {
  //do some stuff here
  resolve(token)
}).then(token => {
  //return missing here
  return Promise.all([configApiPromise(token), simApiPromise(token)]);
}).then(
  results=>{
    console.log("results are:",JSON.stringify(results,undefined,2));
    //returning results again
    return results;
  }
).catch(
  err=>console.warn("Something went wrong:",err)
);

您能否在返回之前记录数据?

.then(function (data) {
  console.log("returning data in configApiFetch:",JSON.stringify(data,undefined,2));
  return data; // here in debugger I see it returns data but in promise.all it returns undefined
});