首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在顺序异步函数中处理数组

如何在顺序异步函数中处理数组
EN

Stack Overflow用户
提问于 2019-09-27 03:23:08
回答 1查看 379关注 0票数 0

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

代码语言:javascript
复制
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()

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-27 03:32:40

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

代码语言:javascript
复制
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)
    }
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58123460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档