我如何使用for循环来重申promise函数?

问题描述 投票:0回答:3

我有以下代码,这些代码用于从Amazon Web Server API获取JSON数据。

var json1 = new Promise((resolve, reject) => {
     fetch(url[0])
     .then(r => {
         resolve(r.json())
     })
     .catch(err => {
         reject(err)
     })
})

我使用不同的url和json vars重复了14次,最后使用使其返回了promises。

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)
        })
    })
}

这不起作用,因为即使由await函数调用了promise函数,其返回的值仍是未定义的。

const data = await fetchURL(urlToQuery())

有人对这项工作有建议吗?返回JSON。

感谢您的帮助。

javascript json for-loop fetch request-promise
3个回答
0
投票

我认为该示例可以为您提供帮助:

// Mock async function
const getDataAsync = callback => {
    setTimeout(
        () => callback(Math.ceil(Math.random() * 100)),
        Math.random() * 1000 + 2000
    )
}

// Create the promise
const getDataWithPromise = () => {
    return new Promise((resolve, reject) => {
        try {
            getDataAsync(resolve);
        } catch(e) {
            reject(e);
        }
    });
}

// Using the promise one time
getDataWithPromise()
    .then(data => console.log("Simple promise:",data))
    .catch(error => console.error(`Error catched ${error}`));

// Promises compound: Promise.all
const promise1 = getDataWithPromise();
promise1.then(data => console.log("promise1 ends:",data));
const promise2 = getDataWithPromise();
promise2.then(data => console.log("promise2 ends:",data));
const promise3 = getDataWithPromise();
promise3.then(data => console.log("promise3 ends:",data));
const promise4 = getDataWithPromise();
promise4.then(data => console.log("promise4 ends:",data));
const promise5 = getDataWithPromise();
promise5.then(data => console.log("promise5 ends:",data));

Promise.all([promise1,promise2,promise3,promise4,promise5])
    .then(data => console.log("Promise all ends !!",data));

希望这会有所帮助


0
投票

您将在闭包和var变量捕获方面遇到问题。

您可能想要更改var以在闭包中捕获正确的值,以便url [jsonCount]实际上是您想要的。

我也认为在一行中执行类似的操作会容易得多:)

let results = [];
for(let i = 0; i < urls.length; ++i) results.push(await (await fetch[urls[i]]).json());

0
投票

这是映射的很好用,将URL映射到promise ...

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())
}
© www.soinside.com 2019 - 2024. All rights reserved.