2016-12-03 77 views
0

我正在執行異步請求以從服務器中提取數據,然後在請求後調用函數。我的問題是如何確保請求已完成,並且在processRecords()運行之前加載了所有數據?運行函數之前如何確保異步請求已完成

在此先感謝。

function getRecords() { 
    var ids = Server.getIds(); 
    var allTheRecords = []; 

    ids.forEach(function(recordId) { 
    Server.getRecord(recordId, function (error, data) { 
     if(error) { 
     console.log(error); 
     } else { 
     allTheRecords.push(data); 
     }; 
    }); 
    }); 

    processRecords(allTheRecords); 
} 

回答

0

你可以使用本地Promise API執行異步操作爲您服務。

使用Promise.all您可以給它一個承諾數組,在調用processRecords函數之前需要解決。

它現在也更具可重用性,因爲您可以在代碼中的其他地方使用getRecord函數。

如果你控制它,你應該想辦法增加從服務器獲取多個記錄的能力。如果你只用一個網絡請求,你並不是真的想要解僱一堆網絡請求。

// Server mock of the api you have shown 
 
const Server = { 
 
    getRecord(id, callback) { 
 
    console.log('getRecord', id) 
 
    callback(null, {id}) 
 
    }, 
 
    getIds() { 
 
    return [1, 2, 3] 
 
    } 
 
} 
 

 
function getRecords (ids, processRecords) { 
 
    console.log('getRecords', ids.join()) 
 
    // mapping the array of id's will convert them to an 
 
    // array of Promises by calling getRecord with the id 
 
    Promise.all(ids.map(getRecord)) 
 
    // then is called once all the promises are resolved 
 
    .then(processRecords) 
 
    // this will be called if the reject function of any 
 
    // promise is called 
 
    .catch(console.error.bind(console)) 
 
} 
 

 
function getRecord(recordId) { 
 
    // this function returns a Promise that wraps your 
 
    // server call 
 
    return new Promise((resolve, reject) => { 
 
    Server.getRecord(recordId, function (error, data) { 
 
     if(error) { 
 
     reject(error) 
 
     } else { 
 
     resolve(data) 
 
     } 
 
    }) 
 
    }) 
 
} 
 

 
getRecords(Server.getIds(), function(records) { 
 
console.log('resolved all promises') 
 
console.log(records) 
 
})

+0

感謝您的反饋。不知道我理解或遵循,雖然:/我無法訪問getRecord函數,因爲它是在一個server.js文件中,爲此練習的目的我無法訪問此文件。我已經讀過關於承諾但尚未實現的任何內容。 –

+0

@LukeAveil找出它在做什麼的最好方法是在devtools中放置斷點並在執行代碼時逐步執行代碼。我已經使用服務器api的模擬對它進行了一些修改,所以它在代碼片段 – synthet1c

0

你是如何執行異步請求?如果這是一個AJAX請求,API將根據調用的結果提供回調。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

+0

中工作。請求被執行'''Server.getRecord()'''。不幸的是,這不是一個AJAX請求......這就是爲什麼我有點掙扎。 –

+0

'服務器'從哪裏來?你在使用什麼API。 –

相關問題