Async and await question, need some help...

Hello there,

I am trying to use the async on fuse. However having an issue which I could not identify.

What I am trying to do is to run the functions in order as ld, id, sd. So that the code will load the data, insert what I want and save afterwards.

However with the help of fuse community I just learned that the load and save commands are asynchronous and the code ran in the order of, insert, load and save.

So I am trying to implement async to my code and following normally should work according to the tutorials.

runfirst();

async function runfirst(){

let dload = await ld();

let dinsert = await id();

let dsave = await sd();

};

function id(){

        hcollection.insert({
	
            _id: 2,

            name: "eren updated 2",

            price: 2222222

        });  

        console.log("insert");

     };

function ld(){	

        hcollection.load(function (err) {

            if (!err) {

                console.log("ld");

                return(true);

            }

        });

    };

function sd(){ 

        hcollection.save(function (err) {

        if (!err) {

        // Save was successful

        console.log("sd");

        return(true);

        }

        });

        
    };

Can anyone help me with this ?

Thanks a lot…

You’re likely after using Promises here, which Fuse JS supports.

The built-in async functions in libraries (such as fetch()) are generally promises too, and you can chain them using doStuff().then(...).then(...) syntax.

Writing your own promise functions is relatively simple:

function doSomething(thing) {
    var p = new Promise(function(resolve, reject) {
        if (thing) {
            resolve("totally true");
        } else {
            reject("not true at all");
        }
    });
    return p;
}

As is using it:

doSomething(true).then(function(x) {
    console.log(x); // logs "totally true" to console
}).catch(function(r) {
    console.log(r); // would log "not true at all" to console, if we passed false to the function call at the top
});

Make as many promises you need, and chain them accordingly to your business logic requirements.