为什么承诺等于"未定义"?

时间:2018-04-17 13:38:29

标签: javascript ajax reactjs promise xmlhttprequest

我试图创建一个简单的加载器,在调用时调用返回数据的API

requestData(pageSize, page, sorted, filtered){
    console.log(filtered);
    var url = `http://www.myurl.com/getProducts?start=${page*pageSize}&end=${page*pageSize+pageSize}`;
    var r = new XMLHttpRequest();
    r.onreadystatechange = function () {
        return new Promise((resolve, reject) =>{
            if (r.readyState != 4 || r.status != 200){
                reject(r);
            } else {
                resolve(r.responseText);
            }
        })
    };
    r.open("GET", url, true);
    r.send(null);
};

fetchData(state, instance) {
    this.setState({ loading: true });

    this.requestData(
      state.pageSize,
      state.page,
      state.sorted,
      state.filtered
    ).then(res => {
        this.setState({
          data: res.rows,
          pages: res.pages,
          loading: false
        });
    });
}

此功能都在React组件中。问题出在最后一个.then()上调用" undefined"宾语。为什么我的承诺没有正确归还?

2 个答案:

答案 0 :(得分:3)

因为你永远不会从requestData返回任何内容。您只需将promise 返回回调函数,该函数将无处可去。您应该将回调包装到promise:

,而不是将promise包装到回调中
function  requestData(pageSize, page, sorted, filtered){
   return new Promise((resolve, reject) =>{
     console.log(filtered);
     var url = `http://www.myurl.com/getProducts?start=${page*pageSize}&end=${page*pageSize+pageSize}`;
    var r = new XMLHttpRequest();

    r.onreadystatechange = function () {        
        if (r.readyState != 4 || r.status != 200){
            reject(r);
        } else {
            resolve(r.responseText);
        }

    };
    r.open("GET", url, true);
    r.send(null);
 });
}

答案 1 :(得分:0)

因为函数requestData没有返回任何内容。你必须像这样返回Promise对象

requestData(pageSize, page, sorted, filtered){
    return new Promise((resolve, reject) => {
        console.log(filtered);
        var url = `http://www.myurl.com/getProducts?start=${page*pageSize}&end=${page*pageSize+pageSize}`;
        var r = new XMLHttpRequest();
        r.onreadystatechange = () => {
            if (r.readyState != 4 || r.status != 200){
                reject(r);
            } else {
                resolve(r.responseText);
            }
        }

        r.open("GET", url, true);
        r.send(null);
    });
}