Async/await is not working

I ran an async function and printed the logs, but the logs were not in the correct sequence.

// pseudo code
 pub async fn execute (id:u32) -> () {
       Self::repay(id, insurance.insurance_asset.clone()).await;
       print("None of the buyers participated".to_owned());
}


 /// Repay the amount to Insurance Contract Sellers
  async fn repay(insurance_id: u32,insurance_asset: InsuranceAssets) -> () {
    
print("Repay to Sellers Start");
print("Ledger Initialization Start");
///Code...
print("Ledger Initialization End");

mutate_state(|s| {
            s.stable_state
           .insurance_sellers
            .iter()
             .filter(|(key, _)| key.insurance_id == insurance_id)
             .for_each(|(k, v)| {
                     
    ic_cdk::println!("Insurance Asset Fee {:?}", insurance_asset_fee);

 spawn(async move {

 let transfer_res: transfer().await;

 match transfer_res {
           TransferSuccess(_) => {
           Self::remove_seller_from_insurance_sellers_list(&key);
          ic_cdk::print("Tranfer Success");
            }}
  })
})
}


/// NOTE : Since there are two entries in a vec
> Output :
Repay to Sellers Start
Ledger Initialization Start
Ledger Initialization End
Insurance Asset Fee Nat(10000)
Insurance Asset Fee Nat(10000)
None of the buyers participated
Tranfer Success
Tranfer Success

> Expected Output :

Repay to Sellers Start
Ledger Initialization Start
Ledger Initialization End
Insurance Asset Fee Nat(10000)
Tranfer Success
Insurance Asset Fee Nat(10000)
Tranfer Success
None of the buyers participated

Is your code really in that horrible mess? I suggest using ´cargo fmt´ to get it formatted into some readable state.

2 Likes

If your wanting a "correct sequence" while keeping spawn;

  • don't use spawn before something you want sequenced before.
  • join the spawned task before something you want sequenced after.
3 Likes

I used below config


edition = "2021"

max_width = 128

single_line_if_else_max_width = 100

remove_nested_parens = true

The code snippet you posted is not formatted by rustfmt - we've seen plenty of rust code you can't fool us! :stuck_out_tongue_closed_eyes:

Rustfmt can bail out and stop formatting for some inputs.

It is also worth running cargo fmt to see if there are any errors, it'll be well worth fixing your formatting setup :slightly_smiling_face:

I can't get that code to format in Zed or with `cargo fmt´. Looks to me like it would never actually compile anyway.

Can we see the actual code that was compiled and run?

let transfer_res: transfer().await;

This is syntactically incorrect and can't be a part of compiled code: in let statement, part after the colon is the type, not the value, and type cannot contain parentheses or dots.

3 Likes