F
F
FinchRED2020-12-07 15:52:43
JavaScript
FinchRED, 2020-12-07 15:52:43

Is it possible to use await/async in this way, returning a result from async to a synchronous function?

Script to integrate quiz with applpplatform .
There are two buttons on the two stages of the quiz.
Inside the synchronous function, I call the async function with fetch api and parse the response, get the id and pass it to the synchronous function, which stupidly writes to the global variable. Because I don’t know how else to save the id of the created contact for the update at the next stage of the quiz.
If it's not difficult, tell me, in general, can such an approach cause bugs. And is it possible somehow better. I just hung the script on two quizzes. One is 10% failure and the other is 90% failure. Although the scripts are identical.

function result_id(result){
 console.log(result);
};
  
         let url =  "https://b24-84z6sr.bitrix24.ru/rest/1/irf1tr07cp90nlym/crm.contact.add.json";
        console.log (url);

         let data = 
          {
            'fields':{
              	    'NAME':'квиз  ',
             		'TITLE': 78888888884,
            		'EMAIL':{'n0':{'VALUE':"[email protected]",
                    'VALUE_TYPE':'WORK'}},
               		"SOURCE_ID": 41996480,     
              	 	"ASSIGNED_BY_ID":1,
              		"OPENED": "Y", 
              		"SOURCE_DESCRIPTION":'( https:/// )'
          			
       				}}			
      
        	async function bitrixHttp(data){    

   		const response = await fetch(url, {
     					method: 'POST', 
       					headers: new Headers(
       						{
       							Accept: 'application/json',
      									'Content-Type': 'application/json'
   							 }),  
   						body: JSON.stringify(data)
  						})
   		console.log("Assynh");
   		let data_res = await response.json(data);
   		await result_id(data_res['result']);	
   		};
   		
   	  setTimeout(bitrixHttp(data),2000);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FODD, 2020-12-07
@FinchRED

You can treat asynchronous functions/promises like a virus - if a function gets into it, everything up the stack should also become asynchronous.
In your case, you can either rewrite everything, or use the good old XMLHTTPRequest in synchronous mode (and put up with blocking the main thread, yes)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question