Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 具有不同超时的同步回调_Javascript_Node.js_Asynchronous_Settimeout - Fatal编程技术网

Javascript 具有不同超时的同步回调

Javascript 具有不同超时的同步回调,javascript,node.js,asynchronous,settimeout,Javascript,Node.js,Asynchronous,Settimeout,我试图使用回调函数进行控制台操作,回调函数本身是setTimeout函数中的回调函数。我怎样才能得到一个有序的结果 我希望调用f1的回调,然后调用f2,最后调用f3,而不管它们的计时器是什么 let f1 = (cb) => { setTimeout(() => { cb(null, {a: 1}) },100) } let f2 = (cb) => { setTimeout(() => { cb(null,

我试图使用回调函数进行控制台操作,回调函数本身是setTimeout函数中的回调函数。我怎样才能得到一个有序的结果

我希望调用f1的回调,然后调用f2,最后调用f3,而不管它们的计时器是什么

let f1 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 1})
    },100)
}

let f2 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 2})
    },50)
}

let f3 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 3})
    },10)
}

function parallelConsole(arr, cb) {
    let result = [];
    arr.forEach(func => {
        func((temp, val) => {
            console.log(val)
            result.push(val)
            if(arr.length === result.length) {
                cb(result)
            }      
        })
    })
}

parallelConsole([f1, f2, f3], (res) => {
    console.log(res) //[{a: 3}, {a: 2}, {a: 1}]
})
预期结果:[{a:1},{a:2},{a:3}]


实际结果:[{a:3},{a:2},{a:1}]

如果您确实需要使用回调,并且这是用于与生产相关的项目,是否使用了一个选项?它提供了一些非常有用的函数(以及
。每一个
都可能是您想要的)

我希望调用f1的回调,然后调用f2,最后调用f3,而不管它们的计时器是什么

let f1 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 1})
    },100)
}

let f2 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 2})
    },50)
}

let f3 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 3})
    },10)
}

function parallelConsole(arr, cb) {
    let result = [];
    arr.forEach(func => {
        func((temp, val) => {
            console.log(val)
            result.push(val)
            if(arr.length === result.length) {
                cb(result)
            }      
        })
    })
}

parallelConsole([f1, f2, f3], (res) => {
    console.log(res) //[{a: 3}, {a: 2}, {a: 1}]
})
我对此有点困惑。如果存在超时,则在指定的时间过后将调用回调。或者,无论何时调用回调,都要以有序的方式(1、2、3)记录
console.log
结果吗

编辑:我已经修改了一点你的代码,所以我认为它符合你的要求。未返回来自
f1、f2、f3
承诺。另外,正如注释中所指出的,使用
Promise.all
可以确保在所有承诺都履行之后调用最终回调

const f1 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 1 }))
  }, 100))
};

const f2 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 2 }))
  }, 50))
};

const f3 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 3 }))
  }, 10))
};

function parallelConsole(arr, cb) {
  return Promise.all(arr)
    .then((values) => {
      cb(null, values);
    });
}

const log = (err, data) => {
  if (err) {
    // TODO: handle properly
    return console.log(err);
  }

  return data;
};

parallelConsole([f1(log), f2(log), f3(log)], (err, res) => {
  console.log(res)
});

如果您真的必须处理回调,并且这是针对与生产相关的项目,是否使用了一个选项?它提供了一些非常有用的函数(以及
。每一个
都可能是您想要的)

我希望调用f1的回调,然后调用f2,最后调用f3,而不管它们的计时器是什么

let f1 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 1})
    },100)
}

let f2 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 2})
    },50)
}

let f3 = (cb) => { 
    setTimeout(() => {
        cb(null, {a: 3})
    },10)
}

function parallelConsole(arr, cb) {
    let result = [];
    arr.forEach(func => {
        func((temp, val) => {
            console.log(val)
            result.push(val)
            if(arr.length === result.length) {
                cb(result)
            }      
        })
    })
}

parallelConsole([f1, f2, f3], (res) => {
    console.log(res) //[{a: 3}, {a: 2}, {a: 1}]
})
我对此有点困惑。如果存在超时,则在指定的时间过后将调用回调。或者,无论何时调用回调,都要以有序的方式(1、2、3)记录
console.log
结果吗

编辑:我已经修改了一点你的代码,所以我认为它符合你的要求。未返回来自
f1、f2、f3
承诺。另外,正如注释中所指出的,使用
Promise.all
可以确保在所有承诺都履行之后调用最终回调

const f1 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 1 }))
  }, 100))
};

const f2 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 2 }))
  }, 50))
};

const f3 = (cb) => {
  return new Promise ((resolve) => setTimeout(() => {
    resolve(cb(null, { a: 3 }))
  }, 10))
};

function parallelConsole(arr, cb) {
  return Promise.all(arr)
    .then((values) => {
      cb(null, values);
    });
}

const log = (err, data) => {
  if (err) {
    // TODO: handle properly
    return console.log(err);
  }

  return data;
};

parallelConsole([f1(log), f2(log), f3(log)], (err, res) => {
  console.log(res)
});

如果您愿意全力以赴而不是回调,代码会变得更加优雅:

// Promisified delay. Resolves with the given optional value after msec.
const delay = (msec, value) =>
  new Promise(resolve => setTimeout(() => resolve(value), msec));

// Call `cb` on the resolved value of `p`; resolve with the same value.
const tapPromise = (p, cb) =>
  p.then(v => {
    cb(v);
    return v;
  });

// Factories for the slow promises
const f1 = () => delay(100, { a: 1 });
const f2 = () => delay(50, { a: 2 });
const f3 = () => delay(10, { a: 3 });

// Create three promises and tap them with console.log.
// (They start executing right away, not when they're waited on.)
const promises = [f1(), f2(), f3()].map(p => tapPromise(p, console.log));

// Wait for all three promises to resolve, then log the results.
// Promise.all guarantees the order is the same as with the original promises.
Promise.all(promises).then(results => {
  console.log(results);
});

如果您愿意全力以赴而不是回调,代码会变得更加优雅:

// Promisified delay. Resolves with the given optional value after msec.
const delay = (msec, value) =>
  new Promise(resolve => setTimeout(() => resolve(value), msec));

// Call `cb` on the resolved value of `p`; resolve with the same value.
const tapPromise = (p, cb) =>
  p.then(v => {
    cb(v);
    return v;
  });

// Factories for the slow promises
const f1 = () => delay(100, { a: 1 });
const f2 = () => delay(50, { a: 2 });
const f3 = () => delay(10, { a: 3 });

// Create three promises and tap them with console.log.
// (They start executing right away, not when they're waited on.)
const promises = [f1(), f2(), f3()].map(p => tapPromise(p, console.log));

// Wait for all three promises to resolve, then log the results.
// Promise.all guarantees the order is the same as with the original promises.
Promise.all(promises).then(results => {
  console.log(results);
});

您是将执行并行化,还是按顺序执行?f3的超时比f2的超时短,f2的超时比f'3的超时短。结果很明显是f3,f2,f1。@Alessandro是的,我希望结果是f1,f2,f3。这就是我在这里的原因。可能是@Alessandro的重复,无论计时器如何,我都希望在结果[0]处有f1。这里是@StefanN,我按照您共享的链接中提到的那样做了。我仍然没有得到预期的结果。链接:您是将执行并行化,还是按顺序执行?f3的超时比f2的超时短,f2的超时比f'3的超时短。结果很明显是f3,f2,f1。@Alessandro是的,我希望结果是f1,f2,f3。这就是我在这里的原因。可能是@Alessandro的重复,无论计时器如何,我都希望在结果[0]处有f1。这里是@StefanN,我按照您共享的链接中提到的那样做了。我仍然没有得到预期的结果。链接:嗨,丹尼,欢迎来到SO!我知道你没有足够的分数发表评论,但这确实不是一个答案。最好是全力以赴兑现承诺,抛弃
cb
,这里:)嗨,丹尼,欢迎来到SO!我知道你没有足够的观点发表评论,但这确实不是一个答案。最好是全力以赴兑现承诺,抛弃
cb
here:)