完成

时间:2015-07-02 19:45:49

标签: javascript node.js

我想在foreach完成后执行回调,但它无法正常工作。我该怎么做?

var response = [];
myArray.forEach(function(data) {
    data.asyncFunction(function(result) {
         response.push(result);
    });
}, function() {
    console.log(response); // Not being called.
});

console.log(response); // (Empty) Executed before foreach finish.

2 个答案:

答案 0 :(得分:8)

因为 v SELECT T.UserID FROM dbo.VacBal as I join dbo.User as T on I.userid = T.userid WHERE VacationBalance > 200 and active = 1 只接受一个/* Reference imports */ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; /* method */ public byte[] getImage(byte[] bytes) throws IOException { int width = 640; int height = 480; int[] shifted = new int[width * height]; // (byte) bgra to rgb (int) for (int i = 0, j = 0; i < bytes.length; i = i + 4, j++) { int b, g, r; b = bytes[i] & 0xFF; g = bytes[i + 1] & 0xFF; r = bytes[i + 2] & 0xFF; shifted[j] = (r << 16) | (g << 8) | b; } BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bufferedImage.getRaster().setDataElements(0, 0, width, height, shifted); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "JPG", baos); byte[] ret = baos.toByteArray(); return ret; } 。由于您在forEach内调用异步方法,因此需要检查是否所有asyn调用都已完成

callback

答案 1 :(得分:3)

试试这个:

myArray.forEach(function(element, index, array){
  asynchronous(function(data){
       if (index === myArray.length - 1) {
           response.push(data);
           functionAfterForEach();
       }
  })
});