2017-08-31 68 views
0

我有一種從API獲取數據驗證碼:的Javascript:camelize所有API響應

const newPromise = Promise.race([ 
    fetch(`${process.env.API_URL}news`), 
    new Promise((resolve, reject) => { 
     setTimeout(() => reject(new Error('request timeout')), 10000) 
    })   
    ]); 

    newPromise 
    .then(response => camelize(response.json())) 
    .then(data => this.onSuccessNewsFetched(data)) 
    .catch(error => this.onErrorNewsFetched(error)) 

我想camelise JSON響應,但它不工作。 我也想對每次獲取的API響應都做這個操作,而不必每次都通過函數調用函數。此外,由於所有對API的請求都需要,超時競爭可能會被抽象化。這怎麼能實現?

回答

2

簡單地寫會爲你的功能和使用,而不是

function betterFetch(url, options = { timeout: 10000 }) { 
    const apiPromise = Promise.race([ 
    fetch(url), 
    new Promise((resolve, reject) => { 
     return setTimeout(() => reject(new Error('request timeout')), options.timeout) 
    }) 
    ]); 

    return apiPromise 
      .then(response => response.json()) 
      .then(data => camelize(data)) 
} 
// later 
betterFetch(`${process.env.API_URL}news`) 
    .then(data => this.onSuccessNewsFetched(data)) 
    .catch(error => this.onErrorNewsFetched(error))