Advertisement
Guest User

Untitled

a guest
Mar 9th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.37 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 callServerAsync(){
  326. $.ajax({
  327. url: '...',
  328. success: function(response) {
  329.  
  330. successCallback(response);
  331. }
  332. });
  333. }
  334.  
  335. function successCallback(responseObj){
  336. // Do something like read the response and show data
  337. alert(JSON.stringify(responseObj)); // Only applicable to JSON response
  338. }
  339.  
  340. function foo(callback) {
  341.  
  342. $.ajax({
  343. url: '...',
  344. success: function(response) {
  345. return callback(null, response);
  346. }
  347. });
  348. }
  349.  
  350. var result = foo(function(err, result){
  351. if (!err)
  352. console.log(result);
  353. });
  354.  
  355. function handleData( responseData ) {
  356.  
  357. // Do what you want with the data
  358. console.log(responseData);
  359. }
  360.  
  361. $.ajax({
  362. url: "hi.php",
  363. ...
  364. success: function ( data, status, XHR ) {
  365. handleData(data);
  366. }
  367. });
  368.  
  369. promiseB = promiseA.then(
  370. function onSuccess(result) {
  371. return result + 1;
  372. }
  373. ,function onError(err) {
  374. //Handle error
  375. }
  376. );
  377.  
  378. // promiseB will be resolved immediately after promiseA is resolved
  379. // and its value will be the result of promiseA incremented by 1.
  380.  
  381. var app = angular.module('plunker', []);
  382.  
  383. app.controller('MainCtrl', function($scope,$http) {
  384.  
  385. var getJoke = function(){
  386. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  387. return res.data.value;
  388. });
  389. }
  390.  
  391. getJoke().then(function(res) {
  392. console.log(res.joke);
  393. });
  394. });
  395.  
  396. var async = require("async");
  397.  
  398. // This wires up result back to the caller
  399. var result = {};
  400. var asyncTasks = [];
  401. asyncTasks.push(function(_callback){
  402. // some asynchronous operation
  403. $.ajax({
  404. url: '...',
  405. success: function(response) {
  406. result.response = response;
  407. _callback();
  408. }
  409. });
  410. });
  411.  
  412. async.parallel(asyncTasks, function(){
  413. // result is available after performing asynchronous operation
  414. console.log(result)
  415. console.log('Done');
  416. });
  417.  
  418. if (!name) {
  419. name = async1();
  420. }
  421. async2(name);
  422.  
  423. async1(name, callback) {
  424. if (name)
  425. callback(name)
  426. else {
  427. doSomething(callback)
  428. }
  429. }
  430.  
  431. async1(name, async2)
  432.  
  433. var Fiber = require('fibers')
  434.  
  435. function async1(container) {
  436. var current = Fiber.current
  437. var result
  438. doSomething(function(name) {
  439. result = name
  440. fiber.run()
  441. })
  442. Fiber.yield()
  443. return result
  444. }
  445.  
  446. Fiber(function() {
  447. var name
  448. if (!name) {
  449. name = async1()
  450. }
  451. async2(name)
  452. // Make any number of async calls from here
  453. }
  454.  
  455. function callback(response) {
  456. // Here you can do what ever you want with the response object.
  457. console.log(response);
  458. }
  459.  
  460. $.ajax({
  461. url: "...",
  462. success: callback
  463. });
  464.  
  465. function $http(apiConfig) {
  466. return new Promise(function (resolve, reject) {
  467. var client = new XMLHttpRequest();
  468. client.open(apiConfig.method, apiConfig.url);
  469. client.send();
  470. client.onload = function () {
  471. if (this.status >= 200 && this.status < 300) {
  472. // Performs the function "resolve" when this.status is equal to 2xx.
  473. // Your logic here.
  474. resolve(this.response);
  475. }
  476. else {
  477. // Performs the function "reject" when this.status is different than 2xx.
  478. reject(this.statusText);
  479. }
  480. };
  481. client.onerror = function () {
  482. reject(this.statusText);
  483. };
  484. });
  485. }
  486.  
  487. $http({
  488. method: 'get',
  489. url: 'google.com'
  490. }).then(function(response) {
  491. console.log(response);
  492. }, function(error) {
  493. console.log(error)
  494. });
  495.  
  496. [
  497. "search?type=playlist&q=%22doom%20metal%22",
  498. "search?type=playlist&q=Adele"
  499. ]
  500.  
  501. function foo(result) {
  502. $.ajax({
  503. url: '...',
  504. success: function(response) {
  505. result.response = response; // Store the async result
  506. }
  507. });
  508. }
  509.  
  510. var result = { response: null }; // Object to hold the async result
  511. foo(result); // Returns before the async completes
  512.  
  513. var result = foo();
  514. // Code that depends on 'result'
  515.  
  516. foo(function(result) {
  517. // Code that depends on 'result'
  518. });
  519.  
  520. function myCallback(result) {
  521. // Code that depends on 'result'
  522. }
  523.  
  524. function foo(callback) {
  525. $.ajax({
  526. // ...
  527. success: callback
  528. });
  529. }
  530.  
  531. function foo(callback) {
  532. $.ajax({
  533. // ...
  534. success: function(response) {
  535. // For example, filter the response
  536. callback(filtered_response);
  537. }
  538. });
  539. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement