2016-09-30 63 views
2

我一直在敲打桌子上我的头在最后几分钟在这里,由于该API的请求......传奇故事,并获取承诺

我有以下代码:

城:

export function * registerFlow() { 
    while (true) { 
    const request = yield take(authTypes.SIGNUP_REQUEST) 
    console.log('authSaga request', request) 
    let response = yield call(authApi.register, request.payload) 
    console.log('authSaga response', response) 
    if (response.error) { 
     return yield put({ type: authTypes.SIGNUP_FAILURE, response }) 
    } 

    yield put({ type: authTypes.SIGNUP_SUCCESS, response }) 
    } 
} 

API请求:

// Inject fetch polyfill if fetch is unsuported 
if (!window.fetch) { const fetch = require('whatwg-fetch') } 

const authApi = { 
    register (userData) { 
    fetch(`http://localhost/api/auth/local/register`, { 
     method : 'POST', 
     headers : { 
     'Accept'  : 'application/json', 
     'Content-Type' : 'application/json' 
     }, 
     body : JSON.stringify({ 
     name  : userData.name, 
     email  : userData.email, 
     password : userData.password 
     }) 
    }) 
    .then(statusHelper) 
    .then(response => response.json()) 
    .catch(error => error) 
    .then(data => data) 
    } 
} 

function statusHelper (response) { 
    if (response.status >= 200 && response.status < 300) { 
    return Promise.resolve(response) 
    } else { 
    return Promise.reject(new Error(response.statusText)) 
    } 
} 

export default authApi 

的API请求,并返回一个有效的对象但是从佐贺调用返回总是未定义的。任何人都可以引导我到哪里我错了?

在此先感谢!

最好的问候,

布鲁诺

+0

'.catch(error => error).then(data => data)''有什么好处?你真的应该省略它们(特别是将每次拒绝转化为履行的'catch') – Bergi

+0

你究竟在哪里得到'undefined'? – Bergi

+0

我在传奇内部得到了undefined,更具体地说,是console.log('authSaga',回应) –

回答

4

你忘了return的承诺从你的函数。做它

const authApi = { 
    register (userData) { 
    return fetch(`http://localhost/api/auth/local/register`, { 
// ^^^^^^ 
     method : 'POST', 
     headers : { 
     'Accept'  : 'application/json', 
     'Content-Type' : 'application/json' 
     }, 
     body : JSON.stringify({ 
     name  : userData.name, 
     email  : userData.email, 
     password : userData.password 
     }) 
    }) 
    .then(statusHelper) 
    .then(response => response.json()); 
    } 
}; 
+0

是的,这是问题所在! 非常感谢! –