[英]How to print the message using setTimeout function with the help of callback and promise concept?
[英]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' ]
我应该在这里做哪些更改?
更新以回应您的评论:
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
:
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.