Guest User

Untitled

a guest
Feb 12th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.03 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. $(document).ready(function(){
  648. function foo() {
  649. $.ajax({url: "api/data", success: function(data){
  650. fooDone(data); //after we have data, we pass it to fooDone
  651. }});
  652. };
  653.  
  654. function fooDone(data) {
  655. console.log(data); //fooDone has the data and console.log it
  656. };
  657.  
  658. foo(); //call happens here
  659. });
  660.  
  661. (async function(){
  662.  
  663. var response = await superagent.get('...')
  664. console.log(response)
  665.  
  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. // do something
  697. return 'wohoo';
  698. }
  699.  
  700. let bar = foo(); // bar is 'wohoo' here
  701.  
  702. function foo(){
  703. setTimeout( ()=>{
  704. return 'wohoo';
  705. }, 1000 )
  706. }
  707.  
  708. let bar = foo() // bar is undefined here
  709.  
  710. function foo(){
  711. return new Promise( (resolve, reject) => { // I want foo() to PROMISE me something
  712. setTimeout ( function(){
  713. // promise is RESOLVED , when exececution reaches this line of code
  714. resolve('wohoo')// After 1 second, RESOLVE the promise with value 'wohoo'
  715. }, 1000 )
  716. })
  717. }
  718.  
  719. let bar ;
  720. foo().then( res => {
  721. bar = res;
  722. console.log(bar) // will print 'wohoo'
  723. });
  724.  
  725. function foo() {
  726. var result;
  727.  
  728. $.ajax({
  729. url: '...',
  730. success: function(response) {
  731. myCallback(response);
  732. }
  733. });
  734.  
  735. return result;
  736. }
  737.  
  738. function myCallback(response) {
  739. // Does something.
  740. }
  741.  
  742. __pragma__ ('alias', 'S', '$')
  743.  
  744. def read(url: str):
  745. deferred = S.Deferred()
  746. S.ajax({'type': "POST", 'url': url, 'data': { },
  747. 'success': lambda d: deferred.resolve(d),
  748. 'error': lambda e: deferred.reject(e)
  749. })
  750. return deferred.promise()
  751.  
  752. async def readALot():
  753. try:
  754. result1 = await read("url_1")
  755. result2 = await read("url_2")
  756. except Exception:
  757. console.warn("Reading a lot failed")
  758.  
  759. var milk = order_milk();
  760. put_in_coffee(milk);
  761.  
  762. order_milk(put_in_coffee);
  763.  
  764. order_milk(function(milk) { put_in_coffee(milk, drink_coffee); }
  765.  
  766. var answer;
  767. $.ajax('/foo.json') . done(function(response) {
  768. callback(response.data);
  769. });
  770.  
  771. function callback(data) {
  772. console.log(data);
  773. }
  774.  
  775. order_milk() . then(put_in_coffee)
  776.  
  777. order_milk() . then(put_in_coffee) . then(drink_coffee)
  778.  
  779. function get_data() {
  780. return $.ajax('/foo.json');
  781. }
  782.  
  783. get_data() . then(do_something)
  784.  
  785. get_data() .
  786. then(function(data) { console.log(data); });
  787.  
  788. get_data() .
  789. then(data => console.log(data));
  790.  
  791. a();
  792. b();
  793.  
  794. a() . then(b);
  795.  
  796. async function morning_routine() {
  797. var milk = await order_milk();
  798. var coffee = await put_in_coffee(milk);
  799. await drink(coffee);
  800. }
  801.  
  802. async function foo() {
  803. data = await get_data();
  804. console.log(data);
  805. }
  806.  
  807. function doAjax(callbackFunc, method, url) {
  808. var xmlHttpReq = new XMLHttpRequest();
  809. xmlHttpReq.open(method, url);
  810. xmlHttpReq.onreadystatechange = function() {
  811.  
  812. if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
  813. callbackFunc(xmlHttpReq.responseText);
  814. }
  815.  
  816.  
  817. }
  818. xmlHttpReq.send(null);
  819.  
  820. }
  821.  
  822. function loadMyJson(categoryValue){
  823. if(categoryValue==="veg")
  824. doAjax(print,"GET","http://localhost:3004/vegetables");
  825. else if(categoryValue==="fruits")
  826. doAjax(print,"GET","http://localhost:3004/fruits");
  827. else
  828. console.log("Data not found");
  829. }
  830.  
  831. async function foo() {
  832. var response = await $.ajax({url: '...'})
  833. return response;
  834. }
  835.  
  836. (async function() {
  837. try {
  838. var result = await foo()
  839. console.log(result)
  840. } catch (e) {}
  841. })()
  842.  
  843. foo().then(response => {
  844. console.log(response)
  845.  
  846. }).catch(error => {
  847. console.log(error)
  848.  
  849. })
  850.  
  851. function foo() {
  852.  
  853. var result = $.ajax({
  854. url: '...',
  855. // This success callback is not required. You can remove it.
  856. // Since we are getting at (1)
  857. success: function (response) {
  858. // result = response;
  859. }
  860. });
  861.  
  862. return result;
  863. }
  864.  
  865. // Since this is a Promise object called $Deferred in jQuery
  866. // You can attach a then callback which accepts two callback
  867. // first one success and second one error
  868.  
  869.  
  870. foo().then(
  871. function( response ) {
  872. // This is success callback (1)
  873. console.log('success: ', response);
  874. }, function( xhr ) {
  875. // This is error callback
  876. console.log('error: ', xhr);
  877. }
  878. )
  879.  
  880. To Add async: false is probably your ajax to call synchronous structure. So automatically the ajax response to return.
  881.  
  882. function foo() {
  883. var result;
  884.  
  885. $.ajax({
  886. url: '...',
  887. async:false,
  888. success: function(response) {
  889. result = response;
  890. }
  891. });
  892.  
  893. return result;
Add Comment
Please, Sign In to add comment