Guest User

Untitled

a guest
Dec 6th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.68 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.  
  354.  
  355. function foo(callback) {
  356.  
  357. $.ajax({
  358. url: '...',
  359. success: function(response) {
  360. return callback(null, response);
  361. }
  362. });
  363. }
  364.  
  365. var result = foo(function(err, result){
  366. if (!err)
  367. console.log(result);
  368. });
  369.  
  370. promiseB = promiseA.then(
  371. function onSuccess(result) {
  372. return result + 1;
  373. }
  374. ,function onError(err) {
  375. //Handle error
  376. }
  377. );
  378.  
  379. // promiseB will be resolved immediately after promiseA is resolved
  380. // and its value will be the result of promiseA incremented by 1.
  381.  
  382. var async = require("async");
  383.  
  384. // This wires up result back to the caller
  385. var result = {};
  386. var asyncTasks = [];
  387. asyncTasks.push(function(_callback){
  388. // some asynchronous operation
  389. $.ajax({
  390. url: '...',
  391. success: function(response) {
  392. result.response = response;
  393. _callback();
  394. }
  395. });
  396. });
  397.  
  398. async.parallel(asyncTasks, function(){
  399. // result is available after performing asynchronous operation
  400. console.log(result)
  401. console.log('Done');
  402. });
  403.  
  404. var app = angular.module('plunker', []);
  405.  
  406. app.controller('MainCtrl', function($scope,$http) {
  407.  
  408. var getJoke = function(){
  409. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  410. return res.data.value;
  411. });
  412. }
  413.  
  414. getJoke().then(function(res){
  415. console.log(res.joke);
  416. });
  417.  
  418. });
  419.  
  420. if (!name) {
  421. name = async1();
  422. }
  423. async2(name);
  424.  
  425. async1(name, callback) {
  426. if (name)
  427. callback(name)
  428. else {
  429. doSomething(callback)
  430. }
  431. }
  432.  
  433. async1(name, async2)
  434.  
  435. var Fiber = require('fibers')
  436.  
  437. function async1(container) {
  438. var current = Fiber.current
  439. var result
  440. doSomething(function(name) {
  441. result = name
  442. fiber.run()
  443. })
  444. Fiber.yield()
  445. return result
  446. }
  447.  
  448. Fiber(function() {
  449. var name
  450. if (!name) {
  451. name = async1()
  452. }
  453. async2(name)
  454. // Make any number of async calls from here
  455. }
  456.  
  457. function callback(response) {
  458. // Here you can do what ever you want with the response object.
  459. console.log(response);
  460. }
  461.  
  462. $.ajax({
  463. url: "...",
  464. success: callback
  465. });
  466.  
  467. function $http(apiConfig) {
  468. return new Promise( function (resolve, reject) {
  469. var client = new XMLHttpRequest();
  470. client.open(apiConfig.method, apiConfig.url);
  471. client.send();
  472. client.onload = function () {
  473. if (this.status >= 200 && this.status < 300) {
  474. // Performs the function "resolve" when this.status is equal to 2xx
  475. // Your logic here
  476. resolve(this.response);
  477. } else {
  478. // Performs the function "reject" when this.status is different than 2xx
  479. reject(this.statusText);
  480. }
  481. };
  482. client.onerror = function () {
  483. reject(this.statusText);
  484. };
  485. });
  486. }
  487.  
  488. $http({
  489. method: 'get',
  490. url: 'google.com'
  491. }).then(function(response) {
  492. console.log(response);
  493. }, function(error) {
  494. console.log(error)
  495. });
  496.  
  497. [
  498. "search?type=playlist&q=%22doom%20metal%22",
  499. "search?type=playlist&q=Adele"
  500. ]
  501.  
  502. function foo(result) {
  503. $.ajax({
  504. url: '...',
  505. success: function(response) {
  506. result.response = response; // Store the async result
  507. }
  508. });
  509. }
  510.  
  511. var result = { response: null }; // Object to hold the async result
  512. foo(result); // Returns before the async completes
Add Comment
Please, Sign In to add comment