在异步功能节点js中维护顺序

lmvvr0a8  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(239)

我对nodejs是新手。我想按url的顺序推送文件数组中的元素。但我得到的是随机顺序。下面是相同的代码。谁能告诉我我做错了什么。

const mergePdf =async  (urlArray, files) => {
  for (let i = 0; i < urlArray.length; i++) {
    try {
      const pdfBytes = await fetch(urlArray[i]).then((res) => {
        return res.arrayBuffer();
      });
      let bytes = new Uint8Array(pdfBytes);
      files[i]=bytes;
    } catch (err) {
      console.log(err);
    }
  }
}
toe95027

toe950271#

编写api调用的seprate函数,如

const other_func = (url) => {
  return new Promise(async (resolve) => {//updated line
     try {
       const pdfBytes = await fetch(url).then((res) => {
       let bytes = new Uint8Array(pdfBytes);
       resolve(bytes);// return value pass in resolve method [Updated]
     });

    } catch (err) {
     console.log(err);
    }
 })
}

在原始函数中,使用wait-like调用这个函数

const mergePdf =async  (urlArray, files) => {
 for (let i = 0; i < urlArray.length; i++) {
 files[i] = await other_func(urlArray[i])
 }}

相关问题