How To Store Ajax Success Variable As Variable Outside Of Ajax?
Solution 1:
When using an asynchronous call like $.ajax
or fetch
or XMLHttpRequest
, its callback runs at a [much] later point in the future when the surrounding scope already ran so you need to use the results of the call inside the callback as explained in How do I return the response from an asynchronous call?
Important addition for extension messaging in Chrome
In Chrome, the onMessage API event won't recognize a Promise returned by the listener so to be able to use sendResponse asynchronously you need to return true
from the onMessage listener and call sendResponse in the ajax callback:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'articleUrl') {
$.ajax({
url: '...........',
success(data) {
sendResponse(data);
},
});
returntrue;
}
});
or
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'articleUrl') {
fetch('https://www.example.org').then(r => r.text()).then(sendResponse);
returntrue;
}
});
async
keyword note
Note that you can't mark the onMessage listener with the async
keyword when returning true
because it would actually return a Promise
object to the API, which is not supported in Chrome extensions API. In this case use a separate async function or an async IIFE, example.
P.S. If you use WebExtension polyfill you can return a Promise from the onMessage listener and use async
function as a listener directly. In Firefox this is how the API works out-of-the-box.
Post a Comment for "How To Store Ajax Success Variable As Variable Outside Of Ajax?"