Javascript 如何使用for循环来重申承诺函数?
我有以下代码用于从AmazonWeb服务器API获取JSON数据Javascript 如何使用for循环来重申承诺函数?,javascript,json,for-loop,fetch,request-promise,Javascript,Json,For Loop,Fetch,Request Promise,我有以下代码用于从AmazonWeb服务器API获取JSON数据 var json1 = new Promise((resolve, reject) => { fetch(url[0]) .then(r => { resolve(r.json()) }) .catch(err => { reject(err) }) }) 我使用不同的URL和json变量重复了14次,并在最后使用返回承诺 r
var json1 = new Promise((resolve, reject) => {
fetch(url[0])
.then(r => {
resolve(r.json())
})
.catch(err => {
reject(err)
})
})
我使用不同的URL和json变量重复了14次,并在最后使用返回承诺
return Promise.all([json1,json2,json3,json4,json5,json6,json7,json8,json9,json10,json11,json12,json13,json14]).then(function(values) {
return values;
});
这是可行的,但它占用了150多行。我想创建一个for循环,它使用for循环运行相同的代码。我创造了这个
for(var jsonCount = 0;jsonCount<url.length-1;jsonCount++){
jsonArr[jsonCount] = new Promise((resolve, reject) => {
fetch(url[jsonCount])
.then(r => {
resolve(r.json())
})
.catch(err => {
reject(err)
})
})
}
有没有人对这项工作有什么建议?正在返回JSON
谢谢你的帮助
编辑:下面是一段较大的代码
function fetchURL(urls) {
let fetchJson = url => fetch(url).then(response => response.json());
Promise.all(urls.map(fetchJson)).then(arr => {
return arr;
});
(异步函数(){
const data=await fetchURL(urlToQuery())
控制台日志(数据);
对于(var r=0;r我认为这个例子可以帮助您:
//模拟异步函数
const getDataAsync=回调=>{
设置超时(
()=>回调(Math.ceil(Math.random()*100)),
Math.random()*1000+2000
)
}
//创造承诺
const getDataWithPromise=()=>{
返回新承诺((解决、拒绝)=>{
试一试{
getDataAsync(解析);
}捕获(e){
拒绝(e);
}
});
}
//使用承诺一次
getDataWithPromise()
.then(data=>console.log(“简单承诺:,数据))
.catch(error=>console.error(`error catched${error}`));
//承诺复合词:承诺
const promise1=getDataWithPromise();
然后(data=>console.log(“promise1结束:”,data));
const promise2=getDataWithPromise();
然后(data=>console.log(“promise2结束:”,data));
const promise3=getDataWithPromise();
然后(data=>console.log(“promise3结束:”,data));
const promise4=getDataWithPromise();
然后(data=>console.log(“promise4结束:”,data));
const promise5=getDataWithPromise();
然后(data=>console.log(“promise5结束:”,data));
允诺。全部([允诺人1,允诺人2,允诺人3,允诺人4,允诺人5])
.then(data=>console.log(“Promise all ends!!”,data));
希望这对您有所帮助您将在闭包和var变量捕获方面遇到问题
您可能希望更改var,以便在闭包中捕获正确的值,这样url[jsonCount]实际上就是您想要的
另外,我认为在一行中做这样的事情要容易得多:)
let results=[];
for(设i=0;i
这是映射的一个很好的用途,将URL映射到承诺
function fetchUrls(urls) {
let promises = urls.map(url => fetch(url))
return Promise.all(promises).then(results => {
return results.map(result => result.json())
})
}}
// url is your array of urls (which would be better named as a plural)
fetchUrls(url).then(results => {
// results will be the fetched json
})
使用异步/等待语法(等效含义)
您可以使用.map
进行循环。但不要使用新承诺
。当获取
已经为您提供了新承诺时,您不需要新承诺。
另外,请调用数组url
,而不是url
。复数形式将很好地指示代码的读者它确实是url的集合
下面是它的外观:
let fetchJson = url => fetch(url).then(response => response.json());
Promise.all(urls.map(fetchJson)).then(arr => {
// process your data
for (let obj of arr) {
console.log(obj);
}
});
也许它对你有帮助:@mgm793谢谢你的链接。我得到一个Uncaught SyntaxError:missing)的错误在第二行的参数列表
之后。我试图进行更改,但总是出现此错误。有什么建议吗?你能发布修改后的代码吗?看起来的数量可以吗?我复制并粘贴了你答案中的代码。这就是我所拥有的。let results=[];for(let I=0;I
for(let i=0;i
仍然会遇到相同的错误。url是正在调用的函数中的一个参数。我在使用console.log(arr)时获得了数据
但是当我返回arr;
到异步函数时,我没有得到任何数据。有什么建议吗?我在上面添加了一大块代码。谢谢你的帮助。这是因为你的函数fetchURL
不返回任何内容。你应该返回承诺的承诺。all()
返回。你是怎么做的?对不起,我真的不熟悉承诺。它没有什么特别的。只需在Promise.all
之前加上return
关键字。all
方法返回一个承诺(它只是一个对象),你需要返回它。否则你的函数什么也不返回(未定义
)。
let results = [];
for(let i = 0; i < urls.length; ++i) results.push(await (await fetch[urls[i]]).json());
function fetchUrls(urls) {
let promises = urls.map(url => fetch(url))
return Promise.all(promises).then(results => {
return results.map(result => result.json())
})
}}
// url is your array of urls (which would be better named as a plural)
fetchUrls(url).then(results => {
// results will be the fetched json
})
// this can be called with await from within another async function
async function fetchUrls(urls) {
let promises = urls.map(url => fetch(url))
let results = await Promise.all(promises)
return results.map(result => result.json())
}
let fetchJson = url => fetch(url).then(response => response.json());
Promise.all(urls.map(fetchJson)).then(arr => {
// process your data
for (let obj of arr) {
console.log(obj);
}
});