首页 > 解决方案 > 如何强制异步函数等到另一个函数完成?

问题描述

这是我的代码:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function user() {
    await mylibwrapper(async () => {
        await sleep(1110); // take long time to done
        console.log("fn");
    })
    // This out put must be after fn. How?
    console.log("user");
}
async function mylibwrapper(fn) {
    // We can wrap or mock fb before pass to mainlib
    await mainlib(fn);
    // How to wait until fn be called and finished? Then we can return and let the caller continue
    console.log("mylibwrapper");
}
async function mainlib(fn) {
    await sublib(fn);
}
async function sublib(fn) {
    fn();
}
user();

我正在为我的用户包装一个库。如何强制mylibwrapper等到回调fn完成后再将结果返回给用户?
输出:

mylibwrapper
user
fn

控制台输出中的预期结果是“user”之前的“fn”。你能帮助我吗?

条件:我们不能通过用户或库(mainlib,sublib)更改代码。我们可以在mylibwrapper传递fnmainlib.

标签: javascriptasync-awaites6-promise

解决方案


您需要await fn()sublib(). 如果您想等待它们完成,则需要等待所有承诺。


推荐阅读