Guest User

Untitled

a guest
Nov 7th, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.85 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. // Using 'superagent' which will return a promise.
  36. var superagent = require('superagent')
  37.  
  38. // This is isn't declared as `async` because it already returns a promise
  39. function delay() {
  40. // `delay` returns a promise
  41. return new Promise(function(resolve, reject) {
  42. // Only `delay` is able to resolve or reject the promise
  43. setTimeout(function() {
  44. resolve(42); // After 3 seconds, resolve the promise with value 42
  45. }, 3000);
  46. });
  47. }
  48.  
  49.  
  50. async function getAllBooks() {
  51. try {
  52. // GET a list of book IDs of the current user
  53. var bookIDs = await superagent.get('/user/books');
  54. // wait for a second (just for the sake of this example)
  55. await delay(1000);
  56. // GET information about each book
  57. return await superagent.get('/books/ids='+JSON.stringify(bookIDs));
  58. } catch(error) {
  59. // If any of the awaited promises was rejected, this catch block
  60. // would catch the rejection reason
  61. return null;
  62. }
  63. }
  64.  
  65. // Async functions always return a promise
  66. getAllBooks()
  67. .then(function(books) {
  68. console.log(books);
  69. });
  70.  
  71. var result = foo();
  72. // Code that depends on 'result'
  73.  
  74. foo(function(result) {
  75. // Code that depends on 'result'
  76. });
  77.  
  78. function myCallback(result) {
  79. // Code that depends on 'result'
  80. }
  81.  
  82. foo(myCallback);
  83.  
  84. function foo(callback) {
  85. $.ajax({
  86. // ...
  87. success: callback
  88. });
  89. }
  90.  
  91. function foo(callback) {
  92. $.ajax({
  93. // ...
  94. success: function(response) {
  95. // For example, filter the response
  96. callback(filtered_response);
  97. }
  98. });
  99. }
  100.  
  101. function delay() {
  102. // `delay` returns a promise
  103. return new Promise(function(resolve, reject) {
  104. // Only `delay` is able to resolve or reject the promise
  105. setTimeout(function() {
  106. resolve(42); // After 3 seconds, resolve the promise with value 42
  107. }, 3000);
  108. });
  109. }
  110.  
  111. delay()
  112. .then(function(v) { // `delay` returns a promise
  113. console.log(v); // Log the value once it is resolved
  114. })
  115. .catch(function(v) {
  116. // Or do something else if it is rejected
  117. // (it would not happen in this example, since `reject` is not called).
  118. });
  119.  
  120. function ajax(url) {
  121. return new Promise(function(resolve, reject) {
  122. var xhr = new XMLHttpRequest();
  123. xhr.onload = function() {
  124. resolve(this.responseText);
  125. };
  126. xhr.onerror = reject;
  127. xhr.open('GET', url);
  128. xhr.send();
  129. });
  130. }
  131.  
  132. ajax("/echo/json")
  133. .then(function(result) {
  134. // Code depending on result
  135. })
  136. .catch(function() {
  137. // An error occurred
  138. });
  139.  
  140. function ajax() {
  141. return $.ajax(...);
  142. }
  143.  
  144. ajax().done(function(result) {
  145. // Code depending on result
  146. }).fail(function() {
  147. // An error occurred
  148. });
  149.  
  150. function checkPassword() {
  151. return $.ajax({
  152. url: '/password',
  153. data: {
  154. username: $('#username').val(),
  155. password: $('#password').val()
  156. },
  157. type: 'POST',
  158. dataType: 'json'
  159. });
  160. }
  161.  
  162. if (checkPassword()) {
  163. // Tell the user they're logged in
  164. }
  165.  
  166. checkPassword()
  167. .done(function(r) {
  168. if (r) {
  169. // Tell the user they're logged in
  170. } else {
  171. // Tell the user their password was bad
  172. }
  173. })
  174. .fail(function(x) {
  175. // Tell the user something bad happened
  176. });
  177.  
  178. function foo() {
  179. var jqXHR = $.ajax({
  180. //...
  181. async: false
  182. });
  183. return jqXHR.responseText;
  184. }
  185.  
  186. function foo() {
  187. var httpRequest = new XMLHttpRequest();
  188. httpRequest.open('GET', "/echo/json");
  189. httpRequest.send();
  190. return httpRequest.responseText;
  191. }
  192.  
  193. var result = foo(); // always ends up being 'undefined'
  194.  
  195. function getFive(){
  196. var a;
  197. setTimeout(function(){
  198. a=5;
  199. },10);
  200. return a;
  201. }
  202.  
  203. function onComplete(a){ // When the code completes, do this
  204. alert(a);
  205. }
  206.  
  207. function getFive(whenDone){
  208. var a;
  209. setTimeout(function(){
  210. a=5;
  211. whenDone(a);
  212. },10);
  213. }
  214.  
  215. getFive(onComplete);
  216.  
  217. var request = new XMLHttpRequest();
  218. request.open('GET', 'yourURL', false); // `false` makes the request synchronous
  219. request.send(null);
  220.  
  221. if (request.status === 200) {// That's HTTP for 'ok'
  222. console.log(request.responseText);
  223. }
  224.  
  225. var result = foo();
  226. // code that depends on `result` goes here
  227.  
  228. foo(function(result) {
  229. // code that depends on `result`
  230. });
  231.  
  232. function myHandler(result) {
  233. // code that depends on `result`
  234. }
  235. foo(myHandler);
  236.  
  237. function foo(callback) {
  238. var httpRequest = new XMLHttpRequest();
  239. httpRequest.onload = function(){ // when the request is loaded
  240. callback(httpRequest.responseText);// we're calling our method
  241. };
  242. httpRequest.open('GET', "/echo/json");
  243. httpRequest.send();
  244. }
  245.  
  246. function ajax(a, b, c){ // URL, callback, just a placeholder
  247. c = new XMLHttpRequest;
  248. c.open('GET', a);
  249. c.onload = b;
  250. c.send()
  251. }
  252.  
  253. this.response
  254.  
  255. e.target.response
  256.  
  257. function callback(e){
  258. console.log(this.response);
  259. }
  260. ajax('URL', callback);
  261.  
  262. ajax('URL', function(e){console.log(this.response)});
  263.  
  264. function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
  265. c = new XMLHttpRequest;
  266. c.open(e||'get', a);
  267. c.onload = b;
  268. c.send(d||null)
  269. }
  270.  
  271. x(url, callback); // By default it's get so no need to set
  272. x(url, callback, 'post', {'key': 'val'}); // No need to set post data
  273.  
  274. var fd = new FormData(form);
  275. x(url, callback, 'post', fd);
  276.  
  277. var fd = new FormData();
  278. fd.append('key', 'val')
  279. x(url, callback, 'post', fd);
  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.onerror = error;
  286. c.send(d||null)
  287. }
  288.  
  289. function error(e){
  290. console.log('--Error--', this.type);
  291. console.log('this: ', this);
  292. console.log('Event: ', e)
  293. }
  294. function displayAjax(e){
  295. console.log(e, this);
  296. }
  297. x('WRONGURL', displayAjax);
  298.  
  299. function omg(a, c){ // URL
  300. c = new XMLHttpRequest;
  301. c.open('GET', a, true);
  302. c.send();
  303. return c; // Or c.response
  304. }
  305.  
  306. var res = omg('thisIsGonnaBlockThePage.txt');
  307.  
  308. function handleData( responseData ) {
  309.  
  310. // Do what you want with the data
  311. console.log(responseData);
  312. }
  313.  
  314. $.ajax({
  315. url: "hi.php",
  316. ...
  317. success: function ( data, status, XHR ) {
  318. handleData(data);
  319. }
  320. });
  321.  
  322. function callServerAsync(){
  323. $.ajax({
  324. url: '...',
  325. success: function(response) {
  326.  
  327. successCallback(response);
  328. }
  329. });
  330. }
  331.  
  332. function successCallback(responseObj){
  333. // Do something like read the response and show data
  334. alert(JSON.stringify(responseObj)); // Only applicable to JSON response
  335. }
  336.  
  337. function foo(callback) {
  338.  
  339. $.ajax({
  340. url: '...',
  341. success: function(response) {
  342. return callback(null, response);
  343. }
  344. });
  345. }
  346.  
  347. var result = foo(function(err, result){
  348. if (!err)
  349. console.log(result);
  350. });
  351.  
  352. promiseB = promiseA.then(
  353. function onSuccess(result) {
  354. return result + 1;
  355. }
  356. ,function onError(err) {
  357. //Handle error
  358. }
  359. );
  360.  
  361. // promiseB will be resolved immediately after promiseA is resolved
  362. // and its value will be the result of promiseA incremented by 1.
  363.  
  364. search(term: string) {
  365. return this.http
  366. .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
  367. .map((response) => response.json())
  368. .toPromise();
  369.  
  370. search() {
  371. this.searchService.search(this.searchField.value)
  372. .then((result) => {
  373. this.result = result.artists.items;
  374. })
  375. .catch((error) => console.error(error));
  376. }
  377.  
  378. // WRONG
  379. var results = [];
  380. theArray.forEach(function(entry) {
  381. doSomethingAsync(entry, function(result) {
  382. results.push(result);
  383. });
  384. });
  385. console.log(results); // E.g., using them, returning them, etc.
  386.  
  387. var results = [];
  388. var expecting = theArray.length;
  389. theArray.forEach(function(entry, index) {
  390. doSomethingAsync(entry, function(result) {
  391. results[index] = result;
  392. if (--expecting === 0) {
  393. // Done!
  394. console.log("Results:", results); // E.g., using the results
  395. }
  396. });
  397. });
  398.  
  399. function doSomethingWith(theArray, callback) {
  400. var results = [];
  401. var expecting = theArray.length;
  402. theArray.forEach(function(entry, index) {
  403. doSomethingAsync(entry, function(result) {
  404. results[index] = result;
  405. if (--expecting === 0) {
  406. // Done!
  407. callback(results);
  408. }
  409. });
  410. });
  411. }
  412. doSomethingWith(theArray, function(results) {
  413. console.log("Results:", results);
  414. });
  415.  
  416. function doSomethingWith(theArray) {
  417. return new Promise(function(resolve) {
  418. var results = [];
  419. var expecting = theArray.length;
  420. theArray.forEach(function(entry, index) {
  421. doSomethingAsync(entry, function(result) {
  422. results[index] = result;
  423. if (--expecting === 0) {
  424. // Done!
  425. resolve(results);
  426. }
  427. });
  428. });
  429. });
  430. }
  431. doSomethingWith(theArray).then(function(results) {
  432. console.log("Results:", results);
  433. });
  434.  
  435. function doSomethingWith(theArray) {
  436. return Promise.all(theArray.map(function(entry) {
  437. return doSomethingAsync(entry, function(result) {
  438. results.push(result);
  439. });
  440. }));
  441. }
  442. doSomethingWith(theArray).then(function(results) {
  443. console.log("Results:", results);
  444. });
  445.  
  446. function doSomethingWith(theArray, callback) {
  447. var results = [];
  448. doOne(0);
  449. function doOne(index) {
  450. if (index < theArray.length) {
  451. doSomethingAsync(theArray[index], function(result) {
  452. results.push(result);
  453. doOne(index + 1);
  454. });
  455. } else {
  456. // Done!
  457. callback(results);
  458. }
  459. }
  460. }
  461. doSomethingWith(theArray, function(results) {
  462. console.log("Results:", results);
  463. });
  464.  
  465. async function doSomethingWith(theArray) {
  466. const results = [];
  467. for (const entry of theArray) {
  468. results.push(await doSomethingAsync(entry));
  469. }
  470. return results;
  471. }
  472. doSomethingWith(theArray).then(results => {
  473. console.log("Results:", results);
  474. });
  475.  
  476. function doSomethingWith(theArray) {
  477. return theArray.reduce(function(p, entry) {
  478. return p.then(function(results) {
  479. return doSomethingAsync(entry).then(function(result) {
  480. results.push(result);
  481. return results;
  482. });
  483. });
  484. }, Promise.resolve([]));
  485. }
  486. doSomethingWith(theArray).then(function(results) {
  487. console.log("Results:", results);
  488. });
  489.  
  490. function doSomethingWith(theArray) {
  491. return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
  492. results.push(result);
  493. return results;
  494. })), Promise.resolve([]));
  495. }
  496. doSomethingWith(theArray).then(results => {
  497. console.log("Results:", results);
  498. });
  499.  
  500. var app = angular.module('plunker', []);
  501.  
  502. app.controller('MainCtrl', function($scope,$http) {
  503.  
  504. var getJoke = function(){
  505. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  506. return res.data.value;
  507. });
  508. }
  509.  
  510. getJoke().then(function(res) {
  511. console.log(res.joke);
  512. });
  513. });
  514.  
  515. var async = require("async");
  516.  
  517. // This wires up result back to the caller
  518. var result = {};
  519. var asyncTasks = [];
  520. asyncTasks.push(function(_callback){
  521. // some asynchronous operation
  522. $.ajax({
  523. url: '...',
  524. success: function(response) {
  525. result.response = response;
  526. _callback();
  527. }
  528. });
  529. });
  530.  
  531. async.parallel(asyncTasks, function(){
  532. // result is available after performing asynchronous operation
  533. console.log(result)
  534. console.log('Done');
  535. });
  536.  
  537. if (!name) {
  538. name = async1();
  539. }
  540. async2(name);
  541.  
  542. async1(name, callback) {
  543. if (name)
  544. callback(name)
  545. else {
  546. doSomething(callback)
  547. }
  548. }
  549.  
  550. async1(name, async2)
  551.  
  552. var Fiber = require('fibers')
  553.  
  554. function async1(container) {
  555. var current = Fiber.current
  556. var result
  557. doSomething(function(name) {
  558. result = name
  559. fiber.run()
  560. })
  561. Fiber.yield()
  562. return result
  563. }
  564.  
  565. Fiber(function() {
  566. var name
  567. if (!name) {
  568. name = async1()
  569. }
  570. async2(name)
  571. // Make any number of async calls from here
  572. }
  573.  
  574. function callback(response) {
  575. // Here you can do what ever you want with the response object.
  576. console.log(response);
  577. }
  578.  
  579. $.ajax({
  580. url: "...",
  581. success: callback
  582. });
  583.  
  584. function $http(apiConfig) {
  585. return new Promise(function (resolve, reject) {
  586. var client = new XMLHttpRequest();
  587. client.open(apiConfig.method, apiConfig.url);
  588. client.send();
  589. client.onload = function () {
  590. if (this.status >= 200 && this.status < 300) {
  591. // Performs the function "resolve" when this.status is equal to 2xx.
  592. // Your logic here.
  593. resolve(this.response);
  594. }
  595. else {
  596. // Performs the function "reject" when this.status is different than 2xx.
  597. reject(this.statusText);
  598. }
  599. };
  600. client.onerror = function () {
  601. reject(this.statusText);
  602. };
  603. });
  604. }
  605.  
  606. $http({
  607. method: 'get',
  608. url: 'google.com'
  609. }).then(function(response) {
  610. console.log(response);
  611. }, function(error) {
  612. console.log(error)
  613. });
  614.  
  615. [
  616. "search?type=playlist&q=%22doom%20metal%22",
  617. "search?type=playlist&q=Adele"
  618. ]
  619.  
  620. -H "Authorization: Bearer {your access token}"
  621.  
  622. var ajaxGet = function (ctx,url) {
  623. var res = {};
  624. var ex;
  625. $.ajax(url)
  626. .done(function (data) {
  627. res.data = data;
  628. })
  629. .fail(function(e) {
  630. ex = e;
  631. })
  632. .always(function() {
  633. ctx.resume(ex);
  634. });
  635. return res;
  636. };
  637. ajaxGet.nsynjsHasCallback = true;
  638.  
  639. function process() {
  640. console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
  641. }
  642.  
  643. nsynjs.run(process,this,function () {
  644. console.log("synchronous function finished");
  645. });
  646.  
  647. (async function(){
  648.  
  649. var response = await superagent.get('...')
  650. console.log(response)
  651.  
  652. })()
  653.  
  654. $(document).ready(function(){
  655. function foo() {
  656. $.ajax({url: "api/data", success: function(data){
  657. fooDone(data); //after we have data, we pass it to fooDone
  658. }});
  659. };
  660.  
  661. function fooDone(data) {
  662. console.log(data); //fooDone has the data and console.log it
  663. };
  664.  
  665. foo(); //call happens here
  666. });
  667.  
  668. function foo(result) {
  669. $.ajax({
  670. url: '...',
  671. success: function(response) {
  672. result.response = response; // Store the async result
  673. }
  674. });
  675. }
  676.  
  677. var result = { response: null }; // Object to hold the async result
  678. foo(result); // Returns before the async completes
  679.  
  680. var lat = "";
  681. var lon = "";
  682. function callback(data){
  683. lat = data.lat;
  684. lon = data.lon;
  685. }
  686. function getLoc() {
  687. var url = "http://ip-api.com/json"
  688. $.getJSON(url, function(data) {
  689. callback(data);
  690. });
  691. }
  692.  
  693. getLoc();
  694.  
  695. function foo() {
  696. var result;
  697.  
  698. $.ajax({
  699. url: '...',
  700. success: function(response) {
  701. myCallback(response);
  702. }
  703. });
  704.  
  705. return result;
  706. }
  707.  
  708. function myCallback(response) {
  709. // Does something.
  710. }
  711.  
  712. function foo(){
  713. // do something
  714. return 'wohoo';
  715. }
  716.  
  717. let bar = foo(); // bar is 'wohoo' here
  718.  
  719. function foo(){
  720. setTimeout( ()=>{
  721. return 'wohoo';
  722. }, 1000 )
  723. }
  724.  
  725. let bar = foo() // bar is undefined here
  726.  
  727. function foo(){
  728. return new Promise( (resolve, reject) => {
  729. setTimeout ( function(){
  730. resolve('wohoo')// After 1 second, RESOLVE the promise with value 'wohoo'
  731. }, 1000 )
  732. })
  733. }
  734.  
  735. let bar ;
  736. foo().then( res => {
  737. bar = res;
  738. console.log(bar) // will print 'wohoo'
  739. });
  740.  
  741. function foo() {
  742.  
  743. var result = $.ajax({
  744. url: '...',
  745. // This success callback is not required. You can remove it.
  746. // Since we are getting at (1)
  747. success: function (response) {
  748. // result = response;
  749. }
  750. });
  751.  
  752. return result;
  753. }
  754.  
  755. // Since this is a Promise object called $Deferred in jQuery
  756. // You can attach a then callback which accepts two callback
  757. // first one success and second one error
  758.  
  759.  
  760. foo().then(
  761. function( response ) {
  762. // This is success callback (1)
  763. console.log('success: ', response);
  764. }, function( xhr ) {
  765. // This is error callback
  766. console.log('error: ', xhr);
  767. }
  768. )
  769.  
  770. foo(123).success(function (response) {
  771. console.log(response);
  772. var result = response; //<- This is the response from ajax request.
  773.  
  774. });
  775.  
  776. //ajax call
  777. function foo(id) {
  778. return $.ajax({
  779. url: '/user/foo',
  780. data: {id: id},
  781. dataType: 'json',
  782. type: "POST"
  783. });
  784. }
  785.  
  786. foo(123).done(function (response) {
  787. console.log(response);
  788. });
Add Comment
Please, Sign In to add comment