繁体   English   中英

通过同步聚合 function 调用返回 Promise,使用 setTimeout 驱动回调,基于 promise

[英]Return Promise by Aggregating function calls by synchronous, callback driven using setTimeout, promise based

如何传递等待 setTimeout 完成并返回 promise 的回调。

当从 function 传递回调时,是否可以在此处进行任何调整以解决此问题,这使得 function 在 setTimeout 之后解析

或者在promise.all()之前调用getB并准备好结果等

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' ]

预期的 output 是[ 'A', 'B', 'C' ]但收到[ 'A', undefined, 'C' ]我应该在这里做哪些更改?

更新以回应您的评论

TS游乐场

 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);


原答案:

getB

TS游乐场

 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));

暂无
暂无

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

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