Advertisement
Guest User

Untitled

a guest
Sep 4th, 2016
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.42 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. function error(e){
  306. console.log('--Error--',this.type);
  307. console.log('this: ',this);
  308. console.log('Event: ',e)
  309. }
  310. function displayAjax(e){
  311. console.log(e,this);
  312. }
  313. x('WRONGURL',displayAjax);
  314.  
  315. function omg(a,c){ // Url
  316. c=new XMLHttpRequest;
  317. c.open('GET',a,true);
  318. c.send();
  319. return c; //or c.response
  320. }
  321.  
  322. var res=omg('thisIsGonnaBlockThePage.txt');
  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. var app = angular.module('plunker', []);
  388.  
  389. app.controller('MainCtrl', function($scope,$http) {
  390.  
  391. var getJoke = function(){
  392. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  393. return res.data.value;
  394. });
  395. }
  396.  
  397. getJoke().then(function(res){
  398. console.log(res.joke);
  399. });
  400.  
  401. });
  402.  
  403. if (!name) {
  404. name = async1();
  405. }
  406. async2(name);
  407.  
  408. async1(name, callback) {
  409. if (name)
  410. callback(name)
  411. else {
  412. doSomething(callback)
  413. }
  414. }
  415.  
  416. async1(name, async2)
  417.  
  418. var Fiber = require('fibers')
  419.  
  420. function async1(container) {
  421. var current = Fiber.current
  422. var result
  423. doSomething(function(name) {
  424. result = name
  425. fiber.run()
  426. })
  427. Fiber.yield()
  428. return result
  429. }
  430.  
  431. Fiber(function() {
  432. var name
  433. if (!name) {
  434. name = async1()
  435. }
  436. async2(name)
  437. // Make any number of async calls from here
  438. }
  439.  
  440. function callback(response) {
  441. // Here you can do what ever you want with the response object.
  442. console.log(response);
  443. }
  444.  
  445. $.ajax({
  446. url: "...",
  447. success: callback
  448. });
  449.  
  450. function $http(apiConfig) {
  451. return new Promise( function (resolve, reject) {
  452. var client = new XMLHttpRequest();
  453. client.open(apiConfig.method, apiConfig.url);
  454. client.send();
  455. client.onload = function () {
  456. if (this.status >= 200 && this.status < 300) {
  457. // Performs the function "resolve" when this.status is equal to 2xx
  458. // Your logic here
  459. resolve(this.response);
  460. } else {
  461. // Performs the function "reject" when this.status is different than 2xx
  462. reject(this.statusText);
  463. }
  464. };
  465. client.onerror = function () {
  466. reject(this.statusText);
  467. };
  468. });
  469. }
  470.  
  471. $http({
  472. method: 'get',
  473. url: 'google.com'
  474. }).then(function(response) {
  475. console.log(response);
  476. }, function(error) {
  477. console.log(error)
  478. });
  479.  
  480. [
  481. "search?type=playlist&q=%22doom%20metal%22",
  482. "search?type=playlist&q=Adele"
  483. ]
  484.  
  485. function foo(result) {
  486. $.ajax({
  487. url: '...',
  488. success: function(response) {
  489. result.response = response; // Store the async result
  490. }
  491. });
  492. }
  493.  
  494. var result = { response: null }; // Object to hold the async result
  495. foo(result); // Returns before the async completes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement