Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function foo() {
- var result;
- $.ajax({
- url: '...',
- success: function(response) {
- result = response;
- // return response; // <- I tried that one as well
- }
- });
- return result;
- }
- var result = foo(); // It always ends up being `undefined`.
- 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 item
- });
- doSomethingElse();
- 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).
- });
- 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("/echo/json").then(function(result) {
- // Code depending on result
- }).catch(function() {
- // An error occurred
- });
- 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;
- }
- 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();
- }
- 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 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 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/node/io only
- yield 1;
- yield 2;
- while(true) yield 3;
- }
- var foo = coroutine(function*(){
- var data = yield fetch("/echo/json"); // notice the yield
- // 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
- // server call done here, 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 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
- }
- 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');
- function handleData( responseData ) {
- // Do what you want with the data
- console.log(responseData);
- }
- $.ajax({
- url: "hi.php",
- ...
- success: function ( data, status, XHR ) {
- handleData(data);
- }
- });
- function callServerAsync(){
- $.ajax({
- url: '...',
- success: function(response) {
- successCallback(response);
- }
- });
- }
- function successCallback(responseObj){
- // Do something like read the response and show data
- alert(JSON.stringify(responseObj)); // Only applicable to JSON response
- }
- function foo(callback) {
- $.ajax({
- url: '...',
- success: function(response) {
- return callback(null, response);
- }
- });
- }
- var result = foo(function(err, result){
- if (!err)
- console.log(result);
- });
- promiseB = promiseA.then(
- function onSuccess(result) {
- return result + 1;
- }
- ,function onError(err) {
- //Handle error
- }
- );
- // promiseB will be resolved immediately after promiseA is resolved
- // and its value will be the result of promiseA incremented by 1.
- var app = angular.module('plunker', []);
- app.controller('MainCtrl', function($scope,$http) {
- var getJoke = function(){
- return $http.get('http://api.icndb.com/jokes/random').then(function(res){
- return res.data.value;
- });
- }
- getJoke().then(function(res) {
- console.log(res.joke);
- });
- });
- var async = require("async");
- // This wires up result back to the caller
- var result = {};
- var asyncTasks = [];
- asyncTasks.push(function(_callback){
- // some asynchronous operation
- $.ajax({
- url: '...',
- success: function(response) {
- result.response = response;
- _callback();
- }
- });
- });
- async.parallel(asyncTasks, function(){
- // result is available after performing asynchronous operation
- console.log(result)
- console.log('Done');
- });
- if (!name) {
- name = async1();
- }
- async2(name);
- async1(name, callback) {
- if (name)
- callback(name)
- else {
- doSomething(callback)
- }
- }
- async1(name, async2)
- var Fiber = require('fibers')
- function async1(container) {
- var current = Fiber.current
- var result
- doSomething(function(name) {
- result = name
- fiber.run()
- })
- Fiber.yield()
- return result
- }
- Fiber(function() {
- var name
- if (!name) {
- name = async1()
- }
- async2(name)
- // Make any number of async calls from here
- }
- function callback(response) {
- // Here you can do what ever you want with the response object.
- console.log(response);
- }
- $.ajax({
- url: "...",
- success: callback
- });
- function $http(apiConfig) {
- return new Promise(function (resolve, reject) {
- var client = new XMLHttpRequest();
- client.open(apiConfig.method, apiConfig.url);
- client.send();
- client.onload = function () {
- if (this.status >= 200 && this.status < 300) {
- // Performs the function "resolve" when this.status is equal to 2xx.
- // Your logic here.
- resolve(this.response);
- }
- else {
- // Performs the function "reject" when this.status is different than 2xx.
- reject(this.statusText);
- }
- };
- client.onerror = function () {
- reject(this.statusText);
- };
- });
- }
- $http({
- method: 'get',
- url: 'google.com'
- }).then(function(response) {
- console.log(response);
- }, function(error) {
- console.log(error)
- });
- [
- "search?type=playlist&q=%22doom%20metal%22",
- "search?type=playlist&q=Adele"
- ]
- function foo(result) {
- $.ajax({
- url: '...',
- success: function(response) {
- result.response = response; // Store the async result
- }
- });
- }
- var result = { response: null }; // Object to hold the async result
- foo(result); // Returns before the async completes
- var result = foo();
- // Code that depends on 'result'
- foo(function(result) {
- // Code that depends on 'result'
- });
- function myCallback(result) {
- // Code that depends on 'result'
- }
- function foo(callback) {
- $.ajax({
- // ...
- success: callback
- });
- }
- function foo(callback) {
- $.ajax({
- // ...
- success: function(response) {
- // For example, filter the response
- callback(filtered_response);
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement