Cómo pasar una devolución de llamada que espera a que finalice setTimeout y devolver una promesa.
¿Hay algún ajuste que se pueda hacer aquí para solucionar esto, cuando se pasa una devolución de llamada desde la función que hace que la función se resuelva después de setTimeout?
O llame a getB antes de promise.all promise.all() y mantenga el resultado listo, etc.
function getA() { return "A"; } function getB(callback) { setTimeout(() => { callback("B"); }, 10); } function getC() { return Promise.resolve().then(() => "C"); } function getABC() { //need to work here only const cb = (val) => val; return Promise.all([getA(), getB(cb), getC()]); } getABC().then((arr) => console.log(arr)); // expected output [ 'A', 'B', 'C' ] El resultado esperado es [ 'A', 'B', 'C' ] pero al recibir [ 'A', undefined, 'C' ] ¿qué cambios debo hacer aquí?
Actualización en respuesta a su comentario :
function getA () { return "A"; } function getB (callback) { setTimeout(() => { callback("B"); }, 10); } function getC () { return Promise.resolve().then(() => "C"); } function getABC () { const waitForCallback = (invoker) => new Promise(resolve => invoker(resolve)); return Promise.all([getA(), waitForCallback(getB), getC()]); } getABC().then(console.log);Respuesta original:
Devuelve una promesa de getB :
function getA () { return "A"; } function getB (callback) { return new Promise(resolve => { setTimeout(() => { resolve(callback("B")); }, 10); }); } function getC () { return Promise.resolve("C"); } function getABC () { const cb = (val) => val; return Promise.all([getA(), getB(cb), getC()]); } getABC().then(console.log.bind(console));