运行函数之前如何确保异步请求已完成
我正在执行异步请求以从服务器中提取数据,然后在请求后调用函数。我的问题是如何确保请求已完成,并且在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);
}
你可以使用本地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)
})
你是如何执行异步请求?如果这是一个AJAX请求,API将根据调用的结果提供回调。
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
中工作。请求被执行'''Server.getRecord()'''。不幸的是,这不是一个AJAX请求......这就是为什么我有点挣扎。 –
'服务器'从哪里来?你在使用什么API。 –
感谢您的反馈。不知道我理解或遵循,虽然:/我无法访问getRecord函数,因为它是在一个server.js文件中,为此练习的目的我无法访问此文件。我已经读过关于承诺但尚未实现的任何内容。 –
@LukeAveil找出它在做什么的最好方法是在devtools中放置断点并在执行代码时逐步执行代码。我已经使用服务器api的模拟对它进行了一些修改,所以它在代码片段 – synthet1c