如何按顺序异步函数处理数组

How to process array in sequence async function

我正在尝试使用 Shopify 订单和图片链接制作 table。但是异步循环有问题。每次我 运行 代码命令以错误的顺序出现在控制台中,例如 998、996、1000... 应该是 1000、999、998... 我尝试在不同的地方添加 async 关键字,并在 settimeout 函数中包装一个函数等等,但没有成功。 如何按正确的顺序列出订单? 提前谢谢你。

const {google} = require('googleapis');
const keys = require('./keys.json');
const Shopify = require('shopify-api-node');
const client = new google.auth.JWT(
    keys.client_email,
    null,
    keys.private_key,
    ['https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive.metadata.readonly']
);
const shopify = new Shopify({
  shopName: 'name.myshopify.com',
  apiKey: 'key',
  password: 'pas'
});
const sheets = google.sheets({version: 'v4', auth: client});
const drive = google.drive({version: 'v3', auth: client});

function getLink(){
    client.authorize(()=> gsrun());
}

async function runDrive(ord, sku){
    const resDrive = await drive.files.list({
    pageSize: 1,
    q: `name contains "sku"`,
    spaces: 'drive',
    });
    const files = resDrive.data.files;
    let link;
    if (files.length) {
            link = `https://drive.google.com/file/d/${files[0].id}/view`;
    } else {
    // console.log('No files found.');
    link = 'No files found.';
    }
    console.log([ord, sku, link])
}

async function gsrun(){
    // Shopify - Get orders list
    let orders = await shopify.order.list({ limit: 7 });
    ordersArray = orders.forEach(ord => {
        skuArray = ord.line_items.forEach(async (item) => {
            // Drive - Search for SKUs
            runDrive(ord.order_number, item.sku)
        })
    })
}
getLink()

对于forEach,异步执行的顺序不是顺序的。您可以尝试在 gsrun 函数中使用 for of 而不是 forEach

async function gsrun(){
  // Shopify - Get orders list
  let orders = await shopify.order.list({ limit: 7 });
  for (const ord of orders) {
    for (const item of ord.line_items) {
      await runDrive(ord.order_number, item.sku)
    }
  }
}