Javascript 有没有办法用async/await代替Promise(all)
我有一个URL数组,需要使用promise或async/await从每个URL获取JSON数据。 最后,我需要从源数组中的每个URL获取一个JSON对象数组。 因此,我想知道是否有任何方法可以用async/await替换Promise(all)? 或者在这种情况下,我应该使用承诺而不是异步/等待语法吗?Javascript 有没有办法用async/await代替Promise(all),javascript,promise,async-await,Javascript,Promise,Async Await,我有一个URL数组,需要使用promise或async/await从每个URL获取JSON数据。 最后,我需要从源数组中的每个URL获取一个JSON对象数组。 因此,我想知道是否有任何方法可以用async/await替换Promise(all)? 或者在这种情况下,我应该使用承诺而不是异步/等待语法吗? Thanx我刚刚在另一个问题中添加了这个答案: 有关aync的更多信息,请等待: 其他可能有用的链接: 就我个人而言,我只是使用aync/Wait。例如: // if you want t
Thanx我刚刚在另一个问题中添加了这个答案: 有关aync的更多信息,请等待: 其他可能有用的链接: 就我个人而言,我只是使用aync/Wait。例如:
// if you want to use await keyword, the function should have async keyword before it
exports.callOnStartUp = async function() {
let response;
// Make the call and add response to cache
await callMarketApi().then(data => { // reading the .then here
response = data;
// Run your for each inside here
}).catch(error => {
logger.log.error('ERROR IN callOnStartUp', {
fileName: currentFilename
});
});
}
return response;
}
function callMarketApi() {
// Do something here, I am using an axios call for the example
let url = 'http://some-url-you-want-to-call';
const options = {
method: 'GET',
url
}
return Axios(options).then(response => {// returning the .then
return response.data;
}).catch(error => {
// Commenting the below code as the caller can handle the error
// logger.log.error('ERROR IN callMarketApi for ' + url, {
// fileName: currentFilename
// });
});
}
这回答了你的问题吗
async/await
是调用承诺的语法糖。如果您喜欢使用async/await,或者它使您的代码更易于阅读或(选择原因),那么请务必使用它。你是否对你的代码没有功能上的影响,这是一个偏好的问题。我理解,但我想知道在async/await中是否有任何等价的Promise(all)返回一个新的Promise实例,并且可以使用async/await结构来等待任何Promise<代码>等待承诺。全部(承诺人1,承诺人2)这几乎就是我想知道的!塔克斯