承诺es6和superagent

问题描述:

我试图使用espe承诺superagent。我试图调用一个内部包含superagent请求的函数。承诺es6和superagent

Request.post(buildReq).then(res => { 
if (res.ok) {//process res} 
}); 

这里是函数封装的SuperAgent

static post(params) { 
    superagent 
     .post(params.url) 
     .send(params.payload) 
     .set('Accept', 'application/json') 
     .end((error, res) => { 
     return this.Promise.resolve(res); 
     }) 
     .bind(this); 
    } 

当我改变功能的,以

static post(params) { 
    return Promise.resolve(superagent 
     .post(params.url) 
     .auth(params.auth.username, params.auth.password) 
     .send(params.payload) 
     .set('Accept', 'application/json') 
     .end((error, res) => { 
     return this.Promise.resolve(res); 
     }) 
    ); 
    } 
回我得到一个错误

enter code here Uncaught TypeError: Cannot read property 'then' of undefined

看起来数据是在我的浏览器的开发工具中返回的,但我无法在.then函数中找到它。我怎样才能得到诺言的答复。

end方法回调中返回的内容并不重要,因为它在获取响应并且没有使用回调结果时异步执行。在源代码中查找herehereend方法返回this,所以在你的第二个例子中,你正在解决superagent没有响应。为了让您的回应方法post必须看起来像:

static post(params) { 
    return new Promise((resolve, reject) => { 
     superagent 
      .post(params.url) 
      .auth(params.auth.username, params.auth.password) 
      .send(params.payload) 
      .set('Accept', 'application/json') 
      .end((error, res) => { 
       error ? reject(error) : resolve(res); 
      }); 
    }); 
} 
+0

真棒解决方案。 – Sinux 2016-07-11 09:05:20

有时你想避免因new Promise(...)那么你可以直接使用Promise.rejectPromise.resolve的缩进级别。

static post(params) { 
    return superagent 
      .post(params.url) 
      .auth(params.auth.username, params.auth.password) 
      .send(params.payload) 
      .set('Accept', 'application/json') 
      .end((error, res) => { 
       return error ? Promise.reject(error) : Promise.resolve(res); 
      }); 
    }); 
} 

这是一个比较consise版本,如果你需要它的大量的请求

import request from "superagent"; 

const withPromiseCallback = (resolve, reject) => (error, response) => { 
    if (error) { 
    reject({error}); 
    } else { 
    resolve(response.body); 
    } 
}; 

export const fetchSuggestions = (search) => new Promise((resolve, reject) => 
request. 
    get("/api/auth/get-companies/0/50"). 
    type("form"). 
    set("Accept", "application/json"). 
    query({ 
     search, 
    }). 
    end(withPromiseCallback(resolve, reject)) 
); 

export const fetchInitialInformation =() => new Promise((resolve, reject) => 
    request. 
    get("/api/auth/check"). 
    set("Accept", "application/json"). 
    end(withPromiseCallback(resolve, reject)) 
);