2017-08-01 37 views
0

我目前正在編寫一個節點應用程序,用於檢查某個文件是否存在於特定位置。對於每個應該存在的訂單,我想向我的Woocommerce Api發出放入請求,將訂單狀態更改爲處理。多次收到事件回調

for (i=0; i<my_orders.length; i++) { 
    var exportedThisPdf = true; 
    var orderId = my_orders[i].orderId.toString(); 
    for (p=0; p<my_orders[i].products.length; p++) { 
     var stickerId = my_orders[i].products[p].meta[0].value; 
     if (fs.existsSync('/mypath/test')) { 
     } else { 
      exportedThisPdf = false; 
     } 
    } 
    if (exportedThisPdf == true) { 
     var data = { 
      status: 'processing' 
     }; 
     client.updateStatus(orderId, data, function (err) { 
      if (err) console.log(err); 
     }) 
    } else { 
     var data = { 
      status: 'failed' 
     }; 
     client.updateStatus(orderId, data, function (err) { 
      if (err) console.log(err); 
     }) 
    } 
} 

console.log("callback"); 

現在我想只能繼續當所有我的訂單狀態已成功更新到處理或失敗的碼。

有沒有辦法以乾淨的異步方式解決這個問題? 由於提前

回答

1

你要等待一些承諾。因此,在第一次創建一個全局變量:

var promises = []; 

話,基本上只要我們做某事異步的,我們添加了一個承諾,這個數組,如:

promises.push(new Promise(function(resolve){ 
    client.updateStatus(orderId, data, function (err) { 
     if (err) return console.log(err); 
     resolve(); 
    }) 
})); 

然後如果添加了所有的承諾,我們可以等待其中:

Promise.all(promises) 
.then(function(){ 
    console.log("finished"); 
}); 
+0

不錯,那偉大工程 –

+0

@jan施穆茨歡迎您選擇;) –

1

嘗試此:使用異步模塊

var async = require('async'); 

    async.eachSeries(my_orders, function(order, ordercallback){ 

     async.eachSeries(order.products, function(product, productcallback){ 
      // DO your put logic here 

      client.updateStatus(orderId, data, function (err) { 
       productcallback(); 
       }) 
     }, function(err){ 
     if(!err) ordercallback() 
     }); 

    }); 
+0

爲什麼要使用異步而我們可以用承諾 –