JavaScript Asynchronous Function Question

Asked 2 years ago, Updated 2 years ago, 128 views

Currently, I am having a hard time coding the web with JavaScript.

I'm using a function, and that function receives an external api.

For example, code

func a(id){
  return API(id);      
}

Let's say this.

At this time, func returns 'undefined' without a proper value.

Debugging directly with alert() results in API output well.

But I found out that if you alert both the return value and the API, the API does not output first, but the return is output first and becomes 'undefined'.

Perhaps it's because the API is slow to get and applied asynchronously, but I wonder how to change this asynchronous situation into a synchronous function.

Or if it's not asynchronous or synchronous, I want to know if you solve the problem.

javascript function asynchronous

2022-09-21 16:23

2 Answers

I think you use nodejs to program the web with javascript, but nodejs works asynchronously when processing IO, so it is returned immediately when calling a function. When calling an asynchronous function, use the callback function to process the event. The API function will probably also be able to take the callback function as a factor and process it when the call is over. Therefore, you can deal with it as follows.

func a(id, cb) {
    API(id, cb);
}

Note that cb is a callback function. Also, please refer to the following article to help you understand asynchronous programming.

http://www.nextree.co.kr/p7292/


2022-09-21 16:23

Does the API not support callback?

The code below is from AWSS3 related questions . It is an API that uploads data to Amazon web service.

var s3 = new AWS.S3();

var params = {
//...Optimized
        };

s3.putObject(params, function(err, data) {
    //callback function that informs you of an error when an error occurs and throws data when successful
});

from this type to use a api callback function supports a look?


2022-09-21 16:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.