Guest User

Untitled

a guest
Dec 21st, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.86 KB | None | 0 0
  1. function foo() {
  2. var result;
  3.  
  4. $.ajax({
  5. url: '...',
  6. success: function(response) {
  7. result = response;
  8. // return response; // <- I tried that one as well
  9. }
  10. });
  11.  
  12. return result;
  13. }
  14.  
  15. var result = foo(); // It always ends up being `undefined`.
  16.  
  17. function findItem() {
  18. var item;
  19. while(item_not_found) {
  20. // search
  21. }
  22. return item;
  23. }
  24.  
  25. var item = findItem();
  26.  
  27. // Do something with item
  28. doSomethingElse();
  29.  
  30. findItem(function(item) {
  31. // Do something with item
  32. });
  33. doSomethingElse();
  34.  
  35. var result = foo();
  36. // Code that depends on 'result'
  37.  
  38. foo(function(result) {
  39. // Code that depends on 'result'
  40. });
  41.  
  42. function myCallback(result) {
  43. // Code that depends on 'result'
  44. }
  45.  
  46. foo(myCallback);
  47.  
  48. function foo(callback) {
  49. $.ajax({
  50. // ...
  51. success: callback
  52. });
  53. }
  54.  
  55. function foo(callback) {
  56. $.ajax({
  57. // ...
  58. success: function(response) {
  59. // For example, filter the response
  60. callback(filtered_response);
  61. }
  62. });
  63. }
  64.  
  65. function delay() {
  66. // `delay` returns a promise
  67. return new Promise(function(resolve, reject) {
  68. // Only `delay` is able to resolve or reject the promise
  69. setTimeout(function() {
  70. resolve(42); // After 3 seconds, resolve the promise with value 42
  71. }, 3000);
  72. });
  73. }
  74.  
  75. delay().then(function(v) { // `delay` returns a promise
  76. console.log(v); // Log the value once it is resolved
  77. }).catch(function(v) {
  78. // Or do something else if it is rejected
  79. // (it would not happen in this example, since `reject` is not called).
  80. });
  81.  
  82. function ajax(url) {
  83. return new Promise(function(resolve, reject) {
  84. var xhr = new XMLHttpRequest();
  85. xhr.onload = function() {
  86. resolve(this.responseText);
  87. };
  88. xhr.onerror = reject;
  89. xhr.open('GET', url);
  90. xhr.send();
  91. });
  92. }
  93.  
  94. ajax("/echo/json").then(function(result) {
  95. // Code depending on result
  96. }).catch(function() {
  97. // An error occurred
  98. });
  99.  
  100. function ajax() {
  101. return $.ajax(...);
  102. }
  103.  
  104. ajax().done(function(result) {
  105. // Code depending on result
  106. }).fail(function() {
  107. // An error occurred
  108. });
  109.  
  110. function checkPassword() {
  111. return $.ajax({
  112. url: '/password',
  113. data: {
  114. username: $('#username').val(),
  115. password: $('#password').val()
  116. },
  117. type: 'POST',
  118. dataType: 'json'
  119. });
  120. }
  121.  
  122. if (checkPassword()) {
  123. // Tell the user they're logged in
  124. }
  125.  
  126. checkPassword()
  127. .done(function(r) {
  128. if (r) {
  129. // Tell the user they're logged in
  130. } else {
  131. // Tell the user their password was bad
  132. }
  133. })
  134. .fail(function(x) {
  135. // Tell the user something bad happened
  136. });
  137.  
  138. function foo() {
  139. var jqXHR = $.ajax({
  140. //...
  141. async: false
  142. });
  143. return jqXHR.responseText;
  144. }
  145.  
  146. function foo() {
  147. var httpRequest = new XMLHttpRequest();
  148. httpRequest.open('GET', "/echo/json");
  149. httpRequest.send();
  150. return httpRequest.responseText;
  151. }
  152.  
  153. var result = foo(); // always ends up being 'undefined'
  154.  
  155. function getFive(){
  156. var a;
  157. setTimeout(function(){
  158. a=5;
  159. },10);
  160. return a;
  161. }
  162.  
  163. function onComplete(a){ // When the code completes, do this
  164. alert(a);
  165. }
  166.  
  167. function getFive(whenDone){
  168. var a;
  169. setTimeout(function(){
  170. a=5;
  171. whenDone(a);
  172. },10);
  173. }
  174.  
  175. getFive(onComplete);
  176.  
  177. var request = new XMLHttpRequest();
  178. request.open('GET', 'yourURL', false); // `false` makes the request synchronous
  179. request.send(null);
  180.  
  181. if (request.status === 200) {// That's HTTP for 'ok'
  182. console.log(request.responseText);
  183. }
  184.  
  185. var result = foo();
  186. // code that depends on `result` goes here
  187.  
  188. foo(function(result) {
  189. // code that depends on `result`
  190. });
  191.  
  192. function myHandler(result) {
  193. // code that depends on `result`
  194. }
  195. foo(myHandler);
  196.  
  197. function foo(callback) {
  198. var httpRequest = new XMLHttpRequest();
  199. httpRequest.onload = function(){ // when the request is loaded
  200. callback(httpRequest.responseText);// we're calling our method
  201. };
  202. httpRequest.open('GET', "/echo/json");
  203. httpRequest.send();
  204. }
  205.  
  206. function foo() {
  207. var data;
  208. // or $.get(...).then, or request(...).then, or query(...).then
  209. fetch("/echo/json").then(function(response){
  210. data = response.json();
  211. });
  212. return data;
  213. }
  214.  
  215. var result = foo(); // result is always undefined no matter what.
  216.  
  217. function delay(ms){ // takes amount of milliseconds
  218. // returns a new promise
  219. return new Promise(function(resolve, reject){
  220. setTimeout(function(){ // when the time is up
  221. resolve(); // change the promise to the fulfilled state
  222. }, ms);
  223. });
  224. }
  225.  
  226. function foo() {
  227. // RETURN the promise
  228. return fetch("/echo/json").then(function(response){
  229. return response.json(); // process it inside the `then`
  230. });
  231. }
  232.  
  233. foo().then(function(response){
  234. // access the value inside the `then`
  235. })
  236.  
  237. function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
  238. yield 1;
  239. yield 2;
  240. while(true) yield 3;
  241. }
  242.  
  243. var foo = coroutine(function*(){
  244. var data = yield fetch("/echo/json"); // notice the yield
  245. // code here only executes _after_ the request is done
  246. return data.json(); // data is defined
  247. });
  248.  
  249. var main = coroutine(function*(){
  250. var bar = yield foo(); // wait our earlier coroutine, it returns a promise
  251. // server call done here, code below executes when done
  252. var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
  253. console.log(baz); // runs after both requests done
  254. });
  255. main();
  256.  
  257. async function foo(){
  258. var data = await fetch("/echo/json"); // notice the await
  259. // code here only executes _after_ the request is done
  260. return data.json(); // data is defined
  261. }
  262.  
  263. function ajax(a, b, c){ // URL, callback, just a placeholder
  264. c = new XMLHttpRequest;
  265. c.open('GET', a);
  266. c.onload = b;
  267. c.send()
  268. }
  269.  
  270. this.response
  271.  
  272. e.target.response
  273.  
  274. function callback(e){
  275. console.log(this.response);
  276. }
  277. ajax('URL', callback);
  278.  
  279. ajax('URL', function(e){console.log(this.response)});
  280.  
  281. function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
  282. c = new XMLHttpRequest;
  283. c.open(e||'get', a);
  284. c.onload = b;
  285. c.send(d||null)
  286. }
  287.  
  288. x(url, callback); // By default it's get so no need to set
  289. x(url, callback, 'post', {'key': 'val'}); // No need to set post data
  290.  
  291. var fd = new FormData(form);
  292. x(url, callback, 'post', fd);
  293.  
  294. var fd = new FormData();
  295. fd.append('key', 'val')
  296. x(url, callback, 'post', fd);
  297.  
  298. function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
  299. c = new XMLHttpRequest;
  300. c.open(e||'get', a);
  301. c.onload = b;
  302. c.onerror = error;
  303. c.send(d||null)
  304. }
  305.  
  306. function error(e){
  307. console.log('--Error--', this.type);
  308. console.log('this: ', this);
  309. console.log('Event: ', e)
  310. }
  311. function displayAjax(e){
  312. console.log(e, this);
  313. }
  314. x('WRONGURL', displayAjax);
  315.  
  316. function omg(a, c){ // URL
  317. c = new XMLHttpRequest;
  318. c.open('GET', a, true);
  319. c.send();
  320. return c; // Or c.response
  321. }
  322.  
  323. var res = omg('thisIsGonnaBlockThePage.txt');
  324.  
  325. function handleData( responseData ) {
  326.  
  327. // Do what you want with the data
  328. console.log(responseData);
  329. }
  330.  
  331. $.ajax({
  332. url: "hi.php",
  333. ...
  334. success: function ( data, status, XHR ) {
  335. handleData(data);
  336. }
  337. });
  338.  
  339. function callServerAsync(){
  340. $.ajax({
  341. url: '...',
  342. success: function(response) {
  343.  
  344. successCallback(response);
  345. }
  346. });
  347. }
  348.  
  349. function successCallback(responseObj){
  350. // Do something like read the response and show data
  351. alert(JSON.stringify(responseObj)); // Only applicable to JSON response
  352. }
  353.  
  354.  
  355.  
  356. function foo(callback) {
  357.  
  358. $.ajax({
  359. url: '...',
  360. success: function(response) {
  361. return callback(null, response);
  362. }
  363. });
  364. }
  365.  
  366. var result = foo(function(err, result){
  367. if (!err)
  368. console.log(result);
  369. });
  370.  
  371. promiseB = promiseA.then(
  372. function onSuccess(result) {
  373. return result + 1;
  374. }
  375. ,function onError(err) {
  376. //Handle error
  377. }
  378. );
  379.  
  380. // promiseB will be resolved immediately after promiseA is resolved
  381. // and its value will be the result of promiseA incremented by 1.
  382.  
  383. var async = require("async");
  384.  
  385. // This wires up result back to the caller
  386. var result = {};
  387. var asyncTasks = [];
  388. asyncTasks.push(function(_callback){
  389. // some asynchronous operation
  390. $.ajax({
  391. url: '...',
  392. success: function(response) {
  393. result.response = response;
  394. _callback();
  395. }
  396. });
  397. });
  398.  
  399. async.parallel(asyncTasks, function(){
  400. // result is available after performing asynchronous operation
  401. console.log(result)
  402. console.log('Done');
  403. });
  404.  
  405. var app = angular.module('plunker', []);
  406.  
  407. app.controller('MainCtrl', function($scope,$http) {
  408.  
  409. var getJoke = function(){
  410. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  411. return res.data.value;
  412. });
  413. }
  414.  
  415. getJoke().then(function(res){
  416. console.log(res.joke);
  417. });
  418.  
  419. });
  420.  
  421. if (!name) {
  422. name = async1();
  423. }
  424. async2(name);
  425.  
  426. async1(name, callback) {
  427. if (name)
  428. callback(name)
  429. else {
  430. doSomething(callback)
  431. }
  432. }
  433.  
  434. async1(name, async2)
  435.  
  436. var Fiber = require('fibers')
  437.  
  438. function async1(container) {
  439. var current = Fiber.current
  440. var result
  441. doSomething(function(name) {
  442. result = name
  443. fiber.run()
  444. })
  445. Fiber.yield()
  446. return result
  447. }
  448.  
  449. Fiber(function() {
  450. var name
  451. if (!name) {
  452. name = async1()
  453. }
  454. async2(name)
  455. // Make any number of async calls from here
  456. }
  457.  
  458. function callback(response) {
  459. // Here you can do what ever you want with the response object.
  460. console.log(response);
  461. }
  462.  
  463. $.ajax({
  464. url: "...",
  465. success: callback
  466. });
  467.  
  468. function $http(apiConfig) {
  469. return new Promise(function (resolve, reject) {
  470. var client = new XMLHttpRequest();
  471. client.open(apiConfig.method, apiConfig.url);
  472. client.send();
  473. client.onload = function () {
  474. if (this.status >= 200 && this.status < 300) {
  475. // Performs the function "resolve" when this.status is equal to 2xx.
  476. // Your logic here.
  477. resolve(this.response);
  478. }
  479. else {
  480. // Performs the function "reject" when this.status is different than 2xx.
  481. reject(this.statusText);
  482. }
  483. };
  484. client.onerror = function () {
  485. reject(this.statusText);
  486. };
  487. });
  488. }
  489.  
  490. $http({
  491. method: 'get',
  492. url: 'google.com'
  493. }).then(function(response) {
  494. console.log(response);
  495. }, function(error) {
  496. console.log(error)
  497. });
  498.  
  499. [
  500. "search?type=playlist&q=%22doom%20metal%22",
  501. "search?type=playlist&q=Adele"
  502. ]
  503.  
  504. function foo(result) {
  505. $.ajax({
  506. url: '...',
  507. success: function(response) {
  508. result.response = response; // Store the async result
  509. }
  510. });
  511. }
  512.  
  513. var result = { response: null }; // Object to hold the async result
  514. foo(result); // Returns before the async completes
Add Comment
Please, Sign In to add comment