简体   繁体   English

等待诺言循环

[英]wait for promise in loop

I got this function: 我得到了这个功能:

const upload = (example) => {
    console.log('uploading...');
    return new Promise(function (resolve, reject) {
        resolve & reject
    });
};

I call the function above here: 我在这里调用上面的函数:

const dirents = await fs.readdirSync(path, {withFileTypes:true});
await Promise.all(dirents.map(async (dirent) => {
    await upload(example).then((response) => {
        console.log('success');
    }, (err) => {
        console.log(err);
    });
});

The output should be 输出应为

'uploading' -> 'success' -> 'uploading' ...

But it is actually 但这实际上是

'uploading' -> 'uploading' -> 'success' -> 'success'

I also tried ( for ... of ) but it doesn't work for me neither. 我也尝试了( for ... of ),但这对我也不起作用。

For sequential promises, using a simple loop in an async function is very clear and readable: 对于顺序承诺,在async函数中使用简单的循环非常清晰易读:

 let userIDs = [1, 2, 3]; async function uploadIDS(ids) { for (let id of ids) { let res = await upload(id) console.log("Success:", res) } } const upload = (example) => { console.log('uploading...'); return new Promise(function(resolve, reject) { resolve(example) }); }; uploadIDS(userIDs) 

Here is a modern example using reduce with async/ await (which you can run here ) 这是一个将reduceasync/ await使用的现代示例(您可以在此处运行)

let userIDs = [1,2,3];

userIDs.reduce( async (previousPromise, nextID) => {
  await previousPromise;
  return upload(nextID).then((val) => {
    console.log("success", val);
  })
}, Promise.resolve());


const upload = (id) => {
    console.log('uploading...', id);
    return new Promise(function (resolve, reject) {
        resolve(id);
    });
};

**you can do it also, with Recursion function ** **您还可以使用递归功能**

 //const dirents = await fs.readdirSync(path, {withFileTypes:true});

    const dirents = [1,2,3]


    const upload = (example) => {
        console.log('uploading...');
        return new Promise(function (resolve, reject) {
            resolve(example)
        });
    };

    function callUpload(dirent, length, count) {

        if(count >= dirents.length){
            return;
        }
        upload(dirent).then(() => {
            count += 1;
            console.log("success")
            callUpload(dirents[count], dirents.length, count)
        })
    }
    callUpload(dirents[0], dirents.length, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM