Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

javascript - How to use Promise.all to loop through a list of API calls while also having a delay between each call?

I read through a wide variety of different questions on using axios/fetch/requests to retrieve data from a list of urls (api calls). I realize similar questions have been asked before. I have some code that almost works but I cannot figure out how to delay between the calls. My timeout doesn't work how I want it to. I want it to wait 3000 ms between calls.

const request = require('request');

var requestAsync = function(url) {
    return new Promise((resolve, reject) => setTimeout(() => {
        var req = request(url, (err, response, body) => {
            if (err) return reject(err, response, body);
            resolve(JSON.parse(body));
        });
    },3000))  ;
};

const urls = [
    'https://jsonplaceholder.typicode.com/posts',
    'https://jsonplaceholder.typicode.com/albums',
    'https://jsonplaceholder.typicode.com/users'
];


var fetchURLdata = async function() {
  
    try {
        var data = await Promise.all(urls.map(requestAsync));
        console.log(data)
    } catch (err) {
        console.error(err);
    }
    console.log(data);
}

fetchURLdata();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want the requests to be made serially, rather than in parallel, it'd make more sense to use a for loop:

const requestAsync = (url) => new Promise((resolve, reject) => {
    request(url, (err, response, body) => {
        if (err) reject(err, response, body);
        else resolve(JSON.parse(body));
    });
});

const delay = ms => new Promise(res => setTimeout(res, ms));

const fetchURLdata = async () => {
    try {
        const data = [];
        for (const url of urls) {
            data.push(await requestAsync(url));
            await delay(3000);
        }
        console.log(data);
    } catch (err) {
        console.error(err);
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...