0

EDITED: Tried below suggestions as well as something more, and now this is the code, I pretty much just made it all async await instead of then and catch...

makeNextAccount();
  

  console.log("Making :" + merchantsToCreate.length + " Accounts")

async function makeNextAccount(currentIndex) {
    for (const item of merchantsToCreate) {

try{
    let accId = "";
    
    var createAccBody = JSON.stringify(
        {
        "email":emails[item],
        "firstName":"sdd",
        "lastName":"dgdg"
    });
    
    
    var createAcc = {
      method: 'post',
      url: url1,
      headers: awsHeaders,
      data : createAccBody
    };

    const createdAccResult = await axios(createAcc); // wait for the request to finish

    await Promise.all(createdAccResult);
    console.log('Done!');

    accId = createdAccResult.data.accountId;
    console.log(JSON.stringify("ACCOUNT CREATED:" + accId));
} catch(err) {
    console.log("ERROR Create acc:" + err );
  }

  try{
    var initUnAuthBody = JSON.stringify(
        {
            "accountId": accId
        });
    
    var initUnAuth = {
      method: 'post',
      url: url2,
      headers: awsHeaders,
      data : initUnAuthBody
    };
    
    const initUnAuthResult = await axios(initUnAuth); // wait for the request to finish
    console.log(JSON.stringify("Init unAuth for:" +accId+", with response:" + initUnAuthResult.status));

  }catch(err) {
    console.log("ERROR unautinit:" + err);
  }

  try{
    var provisionBody = JSON.stringify(
        {
            "name":  accId,
            "active": "1"

        });
    
    var provision = {
      method: 'post',
      url: url3,
      headers: awsHeaders,
      data : provisionBody
    };

    const provisionResult = await axios(provision); // wait for the request to finish
    console.log(JSON.stringify("Provision for:" + accId+", with response:" +  provisionResult.status));

}catch(err) {
    console.log("ERROR provision:" + err);
  }

  try{
    var salesForceRecordody = JSON.stringify(
        {
            "email": emails[item],
            "accountId":  accId,

        });
    
    var salesForceRecord = {
      method: 'post',
      url: url4,
      headers: awsHeaders,
      data : salesForceRecordody
    };

    const salesForceRecordResult = await axios(salesForceRecord); // wait for the request to finish

    console.log(JSON.stringify("SalesForce Record for:" +accId+", with response:" + salesForceRecordResult.status));

    accCreatedList.push(accId); // Push to created list only when all steps are done
}catch(err) {
    console.log("ERROR Salesforce:" + err);
  }

    }
 }

And the result of this is, as you can see is returning a 400 error, but I don't know how to get the full response from the server when using async await in axios, it shows it easily when using then and catch but I can only get this simple response.

When printing the body / headers in the console everything seems fine, it's the same request I did before but it fails here for some reason...

Making :3 Accounts
ERROR Create acc:Error: Request failed with status code 400
ERROR unautinit:Error: Request failed with status code 400
ERROR provision:Error: Request failed with status code 400
ERROR Salesforce:Error: Request failed with status code 400
ERROR Create acc:Error: Request failed with status code 400
ERROR unautinit:Error: Request failed with status code 400
ERROR provision:Error: Request failed with status code 400
ERROR Salesforce:Error: Request failed with status code 400
ERROR Create acc:Error: Request failed with status code 400
ERROR unautinit:Error: Request failed with status code 400
ERROR provision:Error: Request failed with status code 400
ERROR Salesforce:Error: Request failed with status code 400

3 Answers 3

1

With async/await this is relatively simple:

for(...) {
   const result = await axios(...); // wait for the request to finish
   // do something with your result
}
Sign up to request clarification or add additional context in comments.

2 Comments

But that has to be placed inside a function if I use await in a loop it says that it must be inside an async function - how do i solve that?
Yeah, you need to put it inside an async function. You should really read up on async/await if you want to do async code in JS. On StackOverflow we try to solve problems others have and teach the person a little. But not give extensive lessons on already well documented things like async/await. @makat
0

Basically, you need to have your function return the Promise that axios is creating. It's a little hard to tell with the spacing of your sample, but it looks like just adding a return to this line will work:

return axios(createAcc)

Then, instead of using a setTimeout and loop, you need to make the first call, wait for it to finish, then in the then() method, make the next call if you have one:

var merchantsToCreate = getFromSomewhere();
var currentIndex = 0;

function makeNextAccount() {
  if (currentIndex < merchantsToCreate.length - 1) {
    currentIndex++;
    accountCreationFlow(merchantsToCreate[i], emails[i])
      .then(makeNextAccount); // <- will make the next account
  }
}

makeNextAccount(); // kick off the "loop"

3 Comments

I tried doing that with await but it seems to be failing for some reason
If you could update your answer with what you tried, maybe we could help. It is an appropriate technique, so it might just be some typo or something.
OKAY - got it all fixed - used a for..in loop and it seems to work, I have no idea why it failed before , I deleted some logging, maybe i broke something and didn't notice
0

The only solution I was able to use to resolve this is:

  1. Using For..in loop that is placed within an async function
  2. Using this way of requesting: const provisionResult = await axios(provision)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.