-1

This is my code:

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

I'm wrapping a library for my user. How can I force mylibwrapper to wait until the callback fn has finished before return the result to the user?
The output:

mylibwrapper
user
fn

The expected result in console output is "fn" before "user". Can you help me?

Conditions: We cannot change the code by user or libs (mainlib, sublib). We just can change the code in mylibwrapper or wrap/mock fn before passing to mainlib.

user229044
  • 232,980
  • 40
  • 330
  • 338
aviit
  • 1,957
  • 1
  • 27
  • 50
  • What is the problem with your code as it is? Does `mainlib` not return a promise? If so, how does `mainlib` work? – Andria Mar 22 '19 at 04:40
  • @ChrisBrownie55: I updated the question. All `async` functions return promise. In this case I just want to control my code `mylibwrapper` to wait `fn` be finished too before return the control to user but I don't know how. – aviit Mar 22 '19 at 04:45
  • Okay, well @y2bd seems to have answered your question, but you probably shouldn't have a `sublib` or a `mylibwrapper` if you can just await `fn` – Andria Mar 22 '19 at 04:50

1 Answers1

0

You need to await fn() within sublib(). All promises need to be awaited if you want to wait for them to finish.

y2bd
  • 5,783
  • 1
  • 22
  • 25
  • I cannot change the code in `mainlib` or `sublib`. I just can change the code in `mylibwrapper` or wrap `fn` before pass it to `mainlib`. – aviit Mar 22 '19 at 04:51
  • Depending on what `fn` does, you might be able to `await` a single invocation of it (stored in a variable) and then pass the consumed Promise into `mainlib`, as if an awaited Promise is awaited again the result will be immediately returned. This won’t work though if you expect mainlib or sublib to modify the promise first, or do any other work first. – y2bd Mar 22 '19 at 04:55