简体   繁体   English

Javascript asyn/await 未按预期运行

[英]Javascript asyn/await not behaving as expected

I am currently trying to get a grip on async/await on javascript but having trouble understanding why 7 is not running at the end of everything.我目前正试图掌握 javascript 上的异步/等待,但无法理解为什么 7 在一切结束时都没有运行。 I know the culprit is calling the axios.get commands causing a delay but why are we not awaiting for them to finish to move on?我知道罪魁祸首是调用 axios.get 命令导致延迟,但为什么我们不等待他们完成继续前进? I thought any await command pauses the event loop until the awaited function returns something.我认为任何 await 命令都会暂停事件循环,直到等待的函数返回某些内容。

Result:结果:

0
1
before 2
1
before 2
7 - Writing to file ----------------------------------------------------------------------------------
(node:21116) UnhandledPromiseRejectionWarning: ReferenceError: result is not defined
    at processOrders (C:\Users\ReactFootwear\Desktop\Nodejs - Shopify Order System\app.js:30:5)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:21116) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21116) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2
3
2
3
4
5
6

My Code我的代码

const axios = require('axios').default;
const excel = require('exceljs');
const imageToBase64 = require('image-to-base64');
const fs = require('fs');


callShopifyOrdersApi();

// Get orders from shopify Api
async function callShopifyOrdersApi(){
  const url = 'https://shopifyurlhere.com/admin/api/2020-10/orders.json?created_at_min=2020-11-14'
  let responseData = await axios.get(url);
  processOrders(responseData.data.orders);

};


function processOrders(orders){
  console.log("Processing orders bitches");
  createWorkbook(orders).then(result => {

    console.log("7 - Writing to file ------------------------------------------------------------");

    var fileName = "Orders.xlsx";
    result.xlsx.writeFile(fileName).then(() => {
    });
  })
};


async function createWorkbook(orders){

    //Creating New Workbook 
    var workbook = new excel.Workbook();

    //Creating Sheet for that particular WorkBook
    var sheetName = 'Sheet1';
    var sheet = workbook.addWorksheet(sheetName);
    sheet.properties.defaultRowHeight = 200;

    //HEADER FORMAT
    sheet.columns = [ {key:"name", header:"name", width: 25}, {key: "address", header: "address"}];

    console.log("0")
    await compileRows(workbook, sheet, orders).then((workbook) => {return workbook})
  }


async function compileRows(workbook, sheet, orders){
  var rows = [];

  orders.forEach(async function (order) {

    order.line_items.forEach(async function (line_item, i) {
      var row = { name: order.customer.first_name , address: order.shipping_address.address1 }
      sheet.addRow(row);

    var img = await mainGetLineItemImg(line_item);
    
    console.log("3");

      if(i == 0){
 
        console.log("4");
        // add image to workbook by buffer
        const imageId2 = await workbook.addImage({
          buffer: fs.readFileSync('/Users/admin/Desktop/test.jpg'),
          extension: 'jpeg',
        });

        console.log("5");
        await sheet.addImage(imageId2, {
          tl: { col: 0, row: 3 },
          ext: { width: 180, height: 180 }
        });
        console.log("6");
      }
    });
  });
}


//GETTING IMAGE BASE 64
async function mainGetLineItemImg(line_item){
  console.log("1");
  var productId = line_item.product_id;
  var variantId = line_item.variant_id;
  console.log("before 2");

  const url = 'https://shopifyurlhere.com/admin/api/2020-10/variants/'+variantId+'.json';
  let responseData = await axios.get(url);
  var imageId = await responseData.data.variant.image_id;

  const url2 = 'https://shopifyurlhere.com/admin/api/2020-10/products/'+productId+'/images/'+imageId+'.json';
  let responseData2 = await axios.get(url2);
  var src = await responseData2.data.image.src;
  var base64code = await imageToBase64(src);


  console.log("2");
  return base64code;
}

Looks like your problem is in the compileRows function.看起来您的问题出在compileRows函数中。 You are calling orders.forEach() , which runs immediately without awaiting any of the async stuff happening in its callback function.您正在调用orders.forEach() ,它会立即运行,而无需等待其回调函数中发生的任何异步内容。 So compileRows completes almost immediately.所以compileRows几乎立即完成。

Instead, use for loops so that you can actually await the asynchronous operations:相反,使用for循环以便您可以实际await异步操作:

async function compileRows(workbook, sheet, orders){
  for (const order of orders) {
    for (let i = 0; i < order.line_items.length; i += 1) {
      const line_item = order.line_items[i];

      var row = { name: order.customer.first_name , address: order.shipping_address.address1 }
      sheet.addRow(row);

      var img = await mainGetLineItemImg(line_item);
    
      console.log("3");

      if(i == 0){
 
        console.log("4");
        // add image to workbook by buffer
        const imageId2 = await workbook.addImage({
          buffer: fs.readFileSync('/Users/admin/Desktop/test.jpg'),
          extension: 'jpeg',
        });

        console.log("5");
        await sheet.addImage(imageId2, {
          tl: { col: 0, row: 3 },
          ext: { width: 180, height: 180 }
        });
        console.log("6");
      }
    }
  }
}

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

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