avatarJen-Hsuan Hsieh (Sean)

Summary

The article discusses the author's journey to successfully return the response of an AJAX call from an AMD module, comparing different methods including Promise, async/await, fetch, and a synchronous AJAX approach.

Abstract

The author of the article, Sean, a software engineer, shares his experience with refactoring AMD modules to handle HTTP requests and return their results. Initially, he encountered difficulties in getting the actual response data, as most methods he tried, such as using Promise, async/await, and fetch, only returned a Promise object. Frustrated with not being able to access the internal PromiseValue, Sean finally found success by using a synchronous AJAX call, which allowed him to directly obtain the response text. The article details his experiments with each method, highlighting the challenges and the ultimate solution that resolved his issue.

Opinions

  • The author felt frustrated when trying to access the internal PromiseValue directly, as it is not accessible.
  • Despite the modern features of JavaScript like Promise and async/await, the author found them insufficient for his specific use case.
  • The author's success with synchronous AJAX suggests a preference for traditional methods when modern asynchronous patterns fail to meet requirements.
  • The article implies a critical view of the complexity of handling asynchronous operations in JavaScript, despite the language's evolution.
  • The author encourages feedback and collaboration by inviting readers to comment on the article and share their insights.

How to return the response of AJAX (asynchronous) call? Compare Promise, async/await, fetch

Introduction

The task I took recently was to refactor AMD modules in the project. A simple challenge is how to launch a request and return the result from an AMD module. What we expect is our modules can return the result from the HTTP request.

I tried several ways to solve this problem. I can only get a Promise object from most of these methods. I felt frustrated about it.

Finally, I got a solution to return the result from my module. This article shares my experiments and hopes it can help you. The following items were the methods I have tried.

  • Promise + AJAX (failed)
  • async/await + AJAX (failed)
  • fetch (failed)
  • AJAX without aync (success)

Use Promise (ES6) — You will only get a Promise object

  • The first method I tried was to use AJAX with Promise as the following code.
var res = new Promise(function (resolve, reject) {
    $.ajax({url: resourceUrl,
        dataType: "script",
        success: function (data) {
            resolve(resources);
        },
        error: function (err) {
            reject(err);
        }
    });
});
console.log(res)
console.log(res.PromiseValue)
return res.PromiseValue // undefined
  • The above statements will return a Promise object. PromiseValue is an internal property and we can‘t access it directly. The value is undefined if you access Promise.PromiseValue.
Copy right@A Layman

Use aync/await (ES7) : You will only get a Promise object as well

  • The next method I try was to use AJAX with async/await as the following code. We still get a Promise object.
const getResource = async() => {
    try {
        var res;
        await $.ajax({
            url: resourceUrl,
            dataType: "script",
            success: function (data) {
                res = resources;
            },
            error: function (err) {
                console.log(err);
            }
        });
        return res;
    } catch (err) {
        console.log(err);
    }
}
var results = await getResource()
return results.PromiseValue // undefined
  • We can print the unwrapped value in then statements. However, we will still get a Promise object when we pass the value out of the function.
Copy right@A Layman

Use fetch : You will only get a Promise object as well

  • The next method I try was to use fetch as the following code.
var res = fetch(stringsResourceUrl, {
    headers: {
        'Content-Type': 'text/javascript'
    }
}).then(resp => resp.text())
console.log(res)
  • we will get the same result as the first example.
Copy right@A Layman

Use Pure AJAX : We will get the response from this method

  • The last method I tried was to use AJAX without aync as the following code.
  • I could get the response and it solved my problem.
var res = $.ajax({
    url: stringsResourceUrl,
    dataType: "script",
    success: function (data) {},
    async: false,
    error: function (err) {
        console.log(err);
    }
}).responseText;
return res;

References

Summary

Thanks for your patient. I am Sean. I work as a software engineer.

This article is my note. Please feel free to give me advice if any mistakes. I am looking forward to your feedback.

Please feel free to clap if this article can help you. Thank you.

You can also subscribe my page on Facebook.

Related topics

How to use the two-way binding in Knout.js and ReactJS?

Learn how to use SignalR to build a chatroom application

My reflection of :

IT & Network:

Database:

Software testing:

Debugging:

DevOps:

JavaScript
Promises
Asynchronous
Software Development
Front End Development
Recommended from ReadMedium