how to store AJAX success variable as variable outside of AJAX?

前端 未结 1 937
渐次进展
渐次进展 2021-01-25 23:19

I used AJAX to get data that I named variable myPubscore. Now I\'m trying to send myPubscore to another js file. myPubscore prints fine in Ajax, but when I print just before sen

相关标签:
1条回答
  • 2021-01-25 23:44

    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);
          },
        });
        return true;
      }
    });
    

    or

    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.type === 'articleUrl') {
        fetch('https://www.example.org').then(r => r.text()).then(sendResponse);
        return true;
      }
    });
    

    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.

    0 讨论(0)
提交回复
热议问题