Advertisement
Guest User

Untitled

a guest
Apr 15th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.24 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 ajax(a,b,c){ // Url, Callback, just a placeholder
  207. c=new XMLHttpRequest;
  208. c.open('GET',a);
  209. c.onload=b;
  210. c.send()
  211. }
  212.  
  213. this.response
  214.  
  215. e.target.response
  216.  
  217. function callback(e){
  218. console.log(this.response);
  219. }
  220. ajax('URL',callback);
  221.  
  222. ajax('URL',function(e){console.log(this.response)});
  223.  
  224. function x(a,b,e,d,c){ // Url,callback,method,formdata or {key:val},placeholder
  225. c=new XMLHttpRequest;
  226. c.open(e||'get',a);
  227. c.onload=b;
  228. c.send(d||null)
  229. }
  230.  
  231. x(url,callback);//by default it's get so no need to set
  232. x(url,callback,'post',{'key':'val'}); //no need to set post data
  233.  
  234. var fd=new FormData(form);
  235. x(url,callback,'post',fd);
  236.  
  237. var fd=new FormData();
  238. fd.append('key','val')
  239. x(url,callback,'post',fd);
  240.  
  241. function x(a,b,e,d,c){ // URL,callback,method,formdata or {key:val},placeholder
  242. c=new XMLHttpRequest;
  243. c.open(e||'get',a);
  244. c.onload=b;
  245. c.onerror=error;
  246. c.send(d||null)
  247. }
  248. function error(e){
  249. console.log('--Error--',this.type);
  250. console.log('this: ',this);
  251. console.log('Event: ',e)
  252. }
  253. function displayAjax(e){
  254. console.log(e,this);
  255. }
  256. x('WRONGURL',displayAjax);
  257.  
  258. function omg(a,c){ // Url
  259. c=new XMLHttpRequest;
  260. c.open('GET',a,true);
  261. c.send();
  262. return c; //or c.response
  263. }
  264.  
  265. var res=omg('thisIsGonnaBlockThePage.txt');
  266.  
  267. function foo() {
  268. var data;
  269. // or $.get(...).then, or request(...).then, or query(...).then
  270. fetch("/echo/json").then(function(response){
  271. data = response.json();
  272. });
  273. return data;
  274. }
  275.  
  276. var result = foo(); // result is always undefined no matter what.
  277.  
  278. function delay(ms){ // takes amount of milliseconds
  279. // returns a new promise
  280. return new Promise(function(resolve, reject){
  281. setTimeout(function(){ // when the time is up
  282. resolve(); // change the promise to the fulfilled state
  283. }, ms);
  284. });
  285. }
  286.  
  287. function foo() {
  288. // RETURN the promise
  289. return fetch("/echo/json").then(function(response){
  290. return response.json(); // process it inside the `then`
  291. });
  292. }
  293.  
  294. foo().then(function(response){
  295. // access the value inside the `then`
  296. })
  297.  
  298. function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
  299. yield 1;
  300. yield 2;
  301. while(true) yield 3;
  302. }
  303.  
  304. var foo = coroutine(function*(){
  305. var data = yield fetch("/echo/json"); // notice the yield
  306. // code here only executes _after_ the request is done
  307. return data.json(); // data is defined
  308. });
  309.  
  310. var main = coroutine(function*(){
  311. var bar = yield foo(); // wait our earlier coroutine, it returns a promise
  312. // server call done here, code below executes when done
  313. var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
  314. console.log(baz); // runs after both requests done
  315. });
  316. main();
  317.  
  318. async function foo(){
  319. var data = await fetch("/echo/json"); // notice the await
  320. // code here only executes _after_ the request is done
  321. return data.json(); // data is defined
  322. }
  323.  
  324. function handleData( responseData ) {
  325.  
  326. // Do what you want with the data
  327. console.log(responseData);
  328. }
  329.  
  330. $.ajax({
  331. url: "hi.php",
  332. ...
  333. success: function ( data, status, XHR ) {
  334. handleData(data);
  335. }
  336. });
  337.  
  338. function callServerAsync(){
  339. $.ajax({
  340. url: '...',
  341. success: function(response) {
  342.  
  343. successCallback(response);
  344. }
  345. });
  346. }
  347.  
  348. function successCallback(responseObj){
  349. // Do something like read the response and show data
  350. alert(JSON.stringify(responseObj)); // Only applicable to JSON response
  351. }
  352.  
  353. promiseB = promiseA.then(
  354. function onSuccess(result) {
  355. return result + 1;
  356. }
  357. ,function onError(err) {
  358. //Handle error
  359. }
  360. );
  361.  
  362. // promiseB will be resolved immediately after promiseA is resolved
  363. // and its value will be the result of promiseA incremented by 1.
  364.  
  365. var async = require("async");
  366.  
  367. // This wires up result back to the caller
  368. var result = {};
  369. var asyncTasks = [];
  370. asyncTasks.push(function(_callback){
  371. // some asynchronous operation
  372. $.ajax({
  373. url: '...',
  374. success: function(response) {
  375. result.response = response;
  376. _callback();
  377. }
  378. });
  379. });
  380.  
  381. async.parallel(asyncTasks, function(){
  382. // result is available after performing asynchronous operation
  383. console.log(result)
  384. console.log('Done');
  385. });
  386.  
  387. if (!name) {
  388. name = async1();
  389. }
  390. async2(name);
  391.  
  392. async1(name, callback) {
  393. if (name)
  394. callback(name)
  395. else {
  396. doSomething(callback)
  397. }
  398. }
  399.  
  400. async1(name, async2)
  401.  
  402. var Fiber = require('fibers')
  403.  
  404. function async1(container) {
  405. var current = Fiber.current
  406. doSomething(function(name) {
  407. container.unshift(name)
  408. fiber.run()
  409. })
  410. Fiber.yield()
  411. }
  412.  
  413. Fiber(function() {
  414. var name
  415. var container = []
  416. if (!name) {
  417. async1(container) // Taking advantage of the fact that arrays are passed by reference
  418. name = container[0]
  419. }
  420. async2(name)
  421. // Make any number of async calls from here
  422. }
  423.  
  424. [
  425. "search?type=playlist&q=%22doom%20metal%22",
  426. "search?type=playlist&q=Adele"
  427. ]
  428.  
  429. function foo(result) {
  430. $.ajax({
  431. url: '...',
  432. success: function(response) {
  433. result.response = response; // Store the async result
  434. }
  435. });
  436. }
  437.  
  438. var result = { response: null }; // Object to hold the async result
  439. foo(result); // Returns before the async completes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement