简体   繁体   中英

How to hold until another function is completed?

I'm work on a pixi program with wechat which many functions cannot work so I write by myself.

There are 3 functions:

export function load(){
   PIXI.loader.add("images/bg.jpg").load(setup);
}

when the load() has completed setup() will be called.

  export const bg;
        function setup(){
        bg=new Sprite(resources["images/bg.jpg"].texture);
    }

in the main function I want to use the bg when the setup function is completed.

the first and second function is in file1.js.And in file2.js which is the main file includes functions:

import * as global from "js/file1.js"
function main(){
    global.load();
    /* is there anyway to wait the setup is completed?*/
    bg.scale.set(0.5);
    /* since the load function completed but the setup is not complete so 
    I cannot use the bg.
}

I do not want to use setTimeOut to ensure the setup is gone. Is there anyway to wait?

I wonder if there could be a singal to the main function? because I will start the load() function in the main() function and wait setup() is completed and I can use the objects initialed in the setup() function.

Yes you can do it with async and await feaatures of javascript. An async function returns when the async task finishes. So for you your code should be like this:

 async function setup(){
    bg = await new Sprite(resources["images/bg.jpg"].texture);
}

In that way a timeout is not needed and this is the correct async way in general.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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