这个问题与如何使用Promise.all获取URL数组除了我想要一个答案不使用Promise.all
。1
URL数组:
urls = ['https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3']
URL的JSON:
{"userId":1,"id":2,"title":"quis ut nam facilis et officia qui",
"completed":false}
{"userId":1,"id":3,"title":"fugiat veniam minus","completed":false}
目标是获得一个对象数组,其中每个对象都包含title
值。
为了让它更有趣一点,我假设已经有了名称的数组,我希望标题数组与之合并:
namesonly = ['two', 'three']
所需的输出是一组对象:
[{"name":"two","loremipsum":"quis ut nam facilis et officia qui"},
{"name":"three","loremipsum":"fugiat veniam minus"}]
其中我已经将属性名称CCD_ 3改变为CCD_。
1我想要解决方案的具体原因而不是使用Promise.all
我想要在Postman脚本中工作的JavaScript代码。在撰写本文时,后者(还(不支持本土承诺。
以下解决方案依赖于这个有用的答案。1
const namesonly = ['two', 'three'];
const urls = ['https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3'];
const titles = [];
let countDown = urls.length;
urls.forEach((url, index) => {
asynchronousCall(url, title => {
titles[index] = title;
if (--countDown === 0) { // Callback for ALL starts on next line.
const names = namesonly.map(value => ({ name: value }));
const fakeLatins = titles.map(value => ({ loremipsum: value }));
const result =
names.map((item, i) => Object.assign({}, item, fakeLatins[i]));
console.log('result:n' + JSON.stringify(result));
}
});
});
function asynchronousCall (url, callback) {
console.log('Starting fetch for "' + url + '".');
fetch(url).then(response => response.json()).then(responseBody => {
console.log(url.slice(-1) + ': ' + responseBody.title + ' ...');
console.log('... fetch for ' + url + ' completed!');
callback(responseBody.title); // Individual callback.
});
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
参考文献
- 密切相关的答案
- 启动许多异步调用并等待所有调用–第二个堆栈代码段
1我故意在代码中留下了很多打印输出。其目的是让人们更容易看到正在发生的事情以及发生的顺序。任何考虑使用该代码的人当然都应该删除部分或全部打印输出。