javascript - Comment retourner la réponse d'un appel asynchrone

Mots clés : javascriptajaxasynchronousjavascript

meilleur 5 Réponses javascript - Comment retourner la réponse d'un appel asynchrone

vote vote

95

function findItem() {     var item;     while(item_not_found) {         // search     }     return item; }  var item = findItem();  // Do something with item doSomethingElse(); 
findItem(function(item) {     // Do something with the item }); doSomethingElse(); 
// Using 'superagent' which will return a promise. var superagent = require('superagent')  // This is isn't declared as `async` because it already returns a promise function delay() {   // `delay` returns a promise   return new Promise(function(resolve, reject) {     // Only `delay` is able to resolve or reject the promise     setTimeout(function() {       resolve(42); // After 3 seconds, resolve the promise with value 42     }, 3000);   }); }  async function getAllBooks() {   try {     // GET a list of book IDs of the current user     var bookIDs = await superagent.get('/user/books');     // wait for 3 seconds (just for the sake of this example)     await delay();     // GET information about each book     return await superagent.get('/books/ids='+JSON.stringify(bookIDs));   } catch(error) {     // If any of the awaited promises was rejected, this catch block     // would catch the rejection reason     return null;   } }  // Start an IIFE to use `await` at the top level (async function(){   let books = await getAllBooks();   console.log(books); })(); 
var result = foo(); // Code that depends on 'result' 
foo(function(result) {     // Code that depends on 'result' }); 
function myCallback(result) {     // Code that depends on 'result' }  foo(myCallback); 
function foo(callback) {     $.ajax({         // ...         success: callback     }); } 
function foo(callback) {     $.ajax({         // ...         success: function(response) {             // For example, filter the response             callback(filtered_response);         }     }); } 
function delay() {   // `delay` returns a promise   return new Promise(function(resolve, reject) {     // Only `delay` is able to resolve or reject the promise     setTimeout(function() {       resolve(42); // After 3 seconds, resolve the promise with value 42     }, 3000);   }); }  delay()   .then(function(v) { // `delay` returns a promise     console.log(v); // Log the value once it is resolved   })   .catch(function(v) {     // Or do something else if it is rejected     // (it would not happen in this example, since `reject` is not called).   });
.as-console-wrapper { max-height: 100% !important; top: 0; }
function ajax(url) {   return new Promise(function(resolve, reject) {     var xhr = new XMLHttpRequest();     xhr.onload = function() {       resolve(this.responseText);     };     xhr.onerror = reject;     xhr.open('GET', url);     xhr.send();   }); }  ajax("https://jsonplaceholder.typicode.com/todos/1")   .then(function(result) {     console.log(result); // Code depending on result   })   .catch(function() {     // An error occurred   });
.as-console-wrapper { max-height: 100% !important; top: 0; }
function ajax() {     return $.ajax(...); }  ajax().done(function(result) {     // Code depending on result }).fail(function() {     // An error occurred }); 
function checkPassword() {     return $.ajax({         url: '/password',         data: {             username: $('#username').val(),             password: $('#password').val()         },         type: 'POST',         dataType: 'json'     }); }  if (checkPassword()) {     // Tell the user they're logged in } 
checkPassword() .done(function(r) {     if (r) {         // Tell the user they're logged in     } else {         // Tell the user their password was bad     } }) .fail(function(x) {     // Tell the user something bad happened }); 
function foo() {     var jqXHR = $.ajax({         //...         async: false     });     return jqXHR.responseText; } 
vote vote

82

function foo() {     var httpRequest = new XMLHttpRequest();     httpRequest.open('GET', "/echo/json");     httpRequest.send();     return httpRequest.responseText; }  var result = foo(); // Always ends up being 'undefined' 
function getFive(){     var a;     setTimeout(function(){          a=5;     },10);     return a; } 
function onComplete(a){ // When the code completes, do this     alert(a); }  function getFive(whenDone){     var a;     setTimeout(function(){          a=5;          whenDone(a);     },10); } 
getFive(onComplete); 
var request = new XMLHttpRequest(); request.open('GET', 'yourURL', false);  // `false` makes the request synchronous request.send(null);  if (request.status === 200) {// That's HTTP for 'ok'   console.log(request.responseText); } 
var result = foo(); // Code that depends on `result` goes here 
foo(function(result) {     // Code that depends on `result` }); 
function myHandler(result) {     // Code that depends on `result` } foo(myHandler); 
function foo(callback) {     var httpRequest = new XMLHttpRequest();     httpRequest.onload = function(){ // When the request is loaded        callback(httpRequest.responseText);// We're calling our method     };     httpRequest.open('GET', "/echo/json");     httpRequest.send(); } 
vote vote

77

function ajax(a, b, c){ // URL, callback, just a placeholder   c = new XMLHttpRequest;   c.open('GET', a);   c.onload = b;   c.send() } 
this.response 
e.target.response 
function callback(e){   console.log(this.response); } ajax('URL', callback); 
ajax('URL', function(e){console.log(this.response)}); 
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder   c = new XMLHttpRequest;   c.open(e||'get', a);   c.onload = b;   c.send(d||null) } 
x(url, callback); // By default it's GET so no need to set x(url, callback, 'post', {'key': 'val'}); // No need to set POST data 
var fd = new FormData(form); x(url, callback, 'post', fd); 
var fd = new FormData(); fd.append('key', 'val') x(url, callback, 'post', fd); 
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder   c = new XMLHttpRequest;   c.open(e||'get', a);   c.onload = b;   c.onerror = error;   c.send(d||null) }  function error(e){   console.log('--Error--', this.type);   console.log('this: ', this);   console.log('Event: ', e) } function displayAjax(e){   console.log(e, this); } x('WRONGURL', displayAjax); 
function omg(a, c){ // URL   c = new XMLHttpRequest;   c.open('GET', a, true);   c.send();   return c; // Or c.response } 
 var res = omg('thisIsGonnaBlockThePage.txt'); 
vote vote

63

function foo() {     var data;     // Or $.get(...).then, or request(...).then, or query(...).then     fetch("/echo/json").then(function(response){         data = response.json();     });     return data; }  var result = foo(); // 'result' is always undefined no matter what. 
    function getFive(){         var data;         setTimeout(function(){ // Set a timer for one second in the future            data = 5; // After a second, do this         }, 1000);         return data;     }     document.body.innerHTML = getFive(); // `undefined` here and not 5
function delay(ms){ // Takes amount of milliseconds     // Returns a new promise     return new Promise(function(resolve, reject){         setTimeout(function(){ // When the time is up,             resolve(); // change the promise to the fulfilled state         }, ms);     }); } 
function delay(ms){ // Takes amount of milliseconds   // Returns a new promise   return new Promise(function(resolve, reject){     setTimeout(function(){ // When the time is up,       resolve(); // change the promise to the fulfilled state     }, ms);   }); }  function getFive(){   // We're RETURNING the promise. Remember, a promise is a wrapper over our value   return delay(100).then(function(){ // When the promise is ready,       return 5; // return the value 5. Promises are all about return values   }) } // We _have_ to wrap it like this in the call site, and we can't access the plain value getFive().then(function(five){    document.body.innerHTML = five; });
function foo() {     // RETURN the promise     return fetch("/echo/json").then(function(response){         return response.json(); // Process it inside the `then`     }); }  foo().then(function(response){     // Access the value inside the `then` }) 
function* foo(){ // Notice the star. This is ES6, so new browsers, Nodes.js, and io.js only     yield 1;     yield 2;     while(true) yield 3; } 
var foo = coroutine(function*(){     var data = yield fetch("/echo/json"); // Notice the yield     // The code here only executes _after_ the request is done     return data.json(); // 'data' is defined }); 
var main = coroutine(function*(){    var bar = yield foo(); // Wait our earlier coroutine. It returns a promise    // The server call is done here, and the code below executes when done    var baz = yield fetch("/api/users/" + bar.userid); // Depends on foo's result    console.log(baz); // Runs after both requests are done }); main(); 
async function foo(){     var data = await fetch("/echo/json"); // Notice the await     // code here only executes _after_ the request is done     return data.json(); // 'data' is defined } 
vote vote

58

function handleData( responseData ) {      // Do what you want with the data     console.log(responseData); }  $.ajax({     url: "hi.php",     ...     success: function ( data, status, XHR ) {         handleData(data);     } }); 

Questions similaires