Search code examples
javascriptasynchronousasync-awaitvelo

How to return asynchronous calls in JavaScript with two callbacks (WIX corvid)


The following asynchronous function returns 2 callbacks, so I did what I usually do to return the response

  1. Added return before the fetch
  2. Added return before the result (json.access_token)

but this time console.log(httpResponse, 'fetch json') is undefined on the console and console.log(json.access_token) return the right value.

What do I need to change?

From client

GetJSON(NewURLCode).then(httpResponse => {
  console.log(httpResponse, 'fetch json')
}

From Server

GetJSON(NewURLCode){
  return fetch("https://accounts.google.com/o/oauth2/token", {
    "method": "post",
    "headers": {
      "Content-Type": 'application/x-www-form-urlencoded'
    },
    'body': data
  }).then((httpResponse) => {
    if (httpResponse.ok) {
      return httpResponse.json();
    } else {
      return Promise.reject("Fetch did not succeed");
    }
  }).then((json) => { 
    console.log(json.access_token)
    return json.access_token
  }).catch(err => console.log(err));
}

Unlike the previous function, the following function has only one promise and returns the right object from the client

client

insert_coll ('Token',toInsert).then((ins_result) => {consule.log(ins_result)}

Backend

insert_coll{
return wixData.update(myCollection, toUpdate, options)
.then( ( results) => {
let item = results; //see item below
return results

} )
.catch( (err) => {
let errorMsg = err;
} );

} 
}

Solution

  • The error was not accrued because of the return statement, I added a return before httpResponse.json();

    It caused because the WIX onReady component called twice...

    So for solving this issue I used the following WIX solution :

    $w.onReady(function () {
      if (wixWindow.rendering.env === "browser") {
    
    //your code
    }})