Advertisement
Guest User

Untitled

a guest
Jul 10th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.97 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 foo() {
  247. var data;
  248. // or $.get(...).then, or request(...).then, or query(...).then
  249. fetch("/echo/json").then(function(response){
  250. data = response.json();
  251. });
  252. return data;
  253. }
  254.  
  255. var result = foo(); // result is always undefined no matter what.
  256.  
  257. function delay(ms){ // takes amount of milliseconds
  258. // returns a new promise
  259. return new Promise(function(resolve, reject){
  260. setTimeout(function(){ // when the time is up
  261. resolve(); // change the promise to the fulfilled state
  262. }, ms);
  263. });
  264. }
  265.  
  266. function foo() {
  267. // RETURN the promise
  268. return fetch("/echo/json").then(function(response){
  269. return response.json(); // process it inside the `then`
  270. });
  271. }
  272.  
  273. foo().then(function(response){
  274. // access the value inside the `then`
  275. })
  276.  
  277. function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
  278. yield 1;
  279. yield 2;
  280. while(true) yield 3;
  281. }
  282.  
  283. var foo = coroutine(function*(){
  284. var data = yield fetch("/echo/json"); // notice the yield
  285. // code here only executes _after_ the request is done
  286. return data.json(); // data is defined
  287. });
  288.  
  289. var main = coroutine(function*(){
  290. var bar = yield foo(); // wait our earlier coroutine, it returns a promise
  291. // server call done here, code below executes when done
  292. var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
  293. console.log(baz); // runs after both requests done
  294. });
  295. main();
  296.  
  297. async function foo(){
  298. var data = await fetch("/echo/json"); // notice the await
  299. // code here only executes _after_ the request is done
  300. return data.json(); // data is defined
  301. }
  302.  
  303. function ajax(a, b, c){ // URL, callback, just a placeholder
  304. c = new XMLHttpRequest;
  305. c.open('GET', a);
  306. c.onload = b;
  307. c.send()
  308. }
  309.  
  310. this.response
  311.  
  312. e.target.response
  313.  
  314. function callback(e){
  315. console.log(this.response);
  316. }
  317. ajax('URL', callback);
  318.  
  319. ajax('URL', function(e){console.log(this.response)});
  320.  
  321. function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
  322. c = new XMLHttpRequest;
  323. c.open(e||'get', a);
  324. c.onload = b;
  325. c.send(d||null)
  326. }
  327.  
  328. x(url, callback); // By default it's get so no need to set
  329. x(url, callback, 'post', {'key': 'val'}); // No need to set post data
  330.  
  331. var fd = new FormData(form);
  332. x(url, callback, 'post', fd);
  333.  
  334. var fd = new FormData();
  335. fd.append('key', 'val')
  336. x(url, callback, 'post', fd);
  337.  
  338. function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
  339. c = new XMLHttpRequest;
  340. c.open(e||'get', a);
  341. c.onload = b;
  342. c.onerror = error;
  343. c.send(d||null)
  344. }
  345.  
  346. function error(e){
  347. console.log('--Error--', this.type);
  348. console.log('this: ', this);
  349. console.log('Event: ', e)
  350. }
  351. function displayAjax(e){
  352. console.log(e, this);
  353. }
  354. x('WRONGURL', displayAjax);
  355.  
  356. function omg(a, c){ // URL
  357. c = new XMLHttpRequest;
  358. c.open('GET', a, true);
  359. c.send();
  360. return c; // Or c.response
  361. }
  362.  
  363. var res = omg('thisIsGonnaBlockThePage.txt');
  364.  
  365. function handleData( responseData ) {
  366.  
  367. // Do what you want with the data
  368. console.log(responseData);
  369. }
  370.  
  371. $.ajax({
  372. url: "hi.php",
  373. ...
  374. success: function ( data, status, XHR ) {
  375. handleData(data);
  376. }
  377. });
  378.  
  379. function callServerAsync(){
  380. $.ajax({
  381. url: '...',
  382. success: function(response) {
  383.  
  384. successCallback(response);
  385. }
  386. });
  387. }
  388.  
  389. function successCallback(responseObj){
  390. // Do something like read the response and show data
  391. alert(JSON.stringify(responseObj)); // Only applicable to JSON response
  392. }
  393.  
  394. function foo(callback) {
  395.  
  396. $.ajax({
  397. url: '...',
  398. success: function(response) {
  399. return callback(null, response);
  400. }
  401. });
  402. }
  403.  
  404. var result = foo(function(err, result){
  405. if (!err)
  406. console.log(result);
  407. });
  408.  
  409. promiseB = promiseA.then(
  410. function onSuccess(result) {
  411. return result + 1;
  412. }
  413. ,function onError(err) {
  414. //Handle error
  415. }
  416. );
  417.  
  418. // promiseB will be resolved immediately after promiseA is resolved
  419. // and its value will be the result of promiseA incremented by 1.
  420.  
  421. search(term: string) {
  422. return this.http
  423. .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
  424. .map((response) => response.json())
  425. .toPromise();
  426.  
  427. search() {
  428. this.searchService.search(this.searchField.value)
  429. .then((result) => {
  430. this.result = result.artists.items;
  431. })
  432. .catch((error) => console.error(error));
  433. }
  434.  
  435. var app = angular.module('plunker', []);
  436.  
  437. app.controller('MainCtrl', function($scope,$http) {
  438.  
  439. var getJoke = function(){
  440. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  441. return res.data.value;
  442. });
  443. }
  444.  
  445. getJoke().then(function(res) {
  446. console.log(res.joke);
  447. });
  448. });
  449.  
  450. var async = require("async");
  451.  
  452. // This wires up result back to the caller
  453. var result = {};
  454. var asyncTasks = [];
  455. asyncTasks.push(function(_callback){
  456. // some asynchronous operation
  457. $.ajax({
  458. url: '...',
  459. success: function(response) {
  460. result.response = response;
  461. _callback();
  462. }
  463. });
  464. });
  465.  
  466. async.parallel(asyncTasks, function(){
  467. // result is available after performing asynchronous operation
  468. console.log(result)
  469. console.log('Done');
  470. });
  471.  
  472. // WRONG
  473. var results = [];
  474. theArray.forEach(function(entry) {
  475. doSomethingAsync(entry, function(result) {
  476. results.push(result);
  477. });
  478. });
  479. console.log(results); // E.g., using them, returning them, etc.
  480.  
  481. var results = [];
  482. var expecting = theArray.length;
  483. theArray.forEach(function(entry, index) {
  484. doSomethingAsync(entry, function(result) {
  485. results[index] = result;
  486. if (--expecting === 0) {
  487. // Done!
  488. console.log("Results:", results); // E.g., using the results
  489. }
  490. });
  491. });
  492.  
  493. function doSomethingWith(theArray, callback) {
  494. var results = [];
  495. var expecting = theArray.length;
  496. theArray.forEach(function(entry, index) {
  497. doSomethingAsync(entry, function(result) {
  498. results[index] = result;
  499. if (--expecting === 0) {
  500. // Done!
  501. callback(results);
  502. }
  503. });
  504. });
  505. }
  506. doSomethingWith(theArray, function(results) {
  507. console.log("Results:", results);
  508. });
  509.  
  510. function doSomethingWith(theArray) {
  511. return new Promise(function(resolve) {
  512. var results = [];
  513. var expecting = theArray.length;
  514. theArray.forEach(function(entry, index) {
  515. doSomethingAsync(entry, function(result) {
  516. results[index] = result;
  517. if (--expecting === 0) {
  518. // Done!
  519. resolve(results);
  520. }
  521. });
  522. });
  523. });
  524. }
  525. doSomethingWith(theArray).then(function(results) {
  526. console.log("Results:", results);
  527. });
  528.  
  529. function doSomethingWith(theArray) {
  530. return Promise.all(theArray.map(function(entry) {
  531. return doSomethingAsync(entry, function(result) {
  532. results.push(result);
  533. });
  534. }));
  535. }
  536. doSomethingWith(theArray).then(function(results) {
  537. console.log("Results:", results);
  538. });
  539.  
  540. function doSomethingWith(theArray, callback) {
  541. var results = [];
  542. doOne(0);
  543. function doOne(index) {
  544. if (index < theArray.length) {
  545. doSomethingAsync(theArray[index], function(result) {
  546. results.push(result);
  547. doOne(index + 1);
  548. });
  549. } else {
  550. // Done!
  551. callback(results);
  552. }
  553. }
  554. }
  555. doSomethingWith(theArray, function(results) {
  556. console.log("Results:", results);
  557. });
  558.  
  559. async function doSomethingWith(theArray) {
  560. const results = [];
  561. for (const entry of theArray) {
  562. results.push(await doSomethingAsync(entry));
  563. }
  564. return results;
  565. }
  566. doSomethingWith(theArray).then(results => {
  567. console.log("Results:", results);
  568. });
  569.  
  570. function doSomethingWith(theArray) {
  571. return theArray.reduce(function(p, entry) {
  572. return p.then(function(results) {
  573. return doSomethingAsync(entry).then(function(result) {
  574. results.push(result);
  575. return results;
  576. });
  577. });
  578. }, Promise.resolve([]));
  579. }
  580. doSomethingWith(theArray).then(function(results) {
  581. console.log("Results:", results);
  582. });
  583.  
  584. function doSomethingWith(theArray) {
  585. return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
  586. results.push(result);
  587. return results;
  588. })), Promise.resolve([]));
  589. }
  590. doSomethingWith(theArray).then(results => {
  591. console.log("Results:", results);
  592. });
  593.  
  594. if (!name) {
  595. name = async1();
  596. }
  597. async2(name);
  598.  
  599. async1(name, callback) {
  600. if (name)
  601. callback(name)
  602. else {
  603. doSomething(callback)
  604. }
  605. }
  606.  
  607. async1(name, async2)
  608.  
  609. var Fiber = require('fibers')
  610.  
  611. function async1(container) {
  612. var current = Fiber.current
  613. var result
  614. doSomething(function(name) {
  615. result = name
  616. fiber.run()
  617. })
  618. Fiber.yield()
  619. return result
  620. }
  621.  
  622. Fiber(function() {
  623. var name
  624. if (!name) {
  625. name = async1()
  626. }
  627. async2(name)
  628. // Make any number of async calls from here
  629. }
  630.  
  631. function callback(response) {
  632. // Here you can do what ever you want with the response object.
  633. console.log(response);
  634. }
  635.  
  636. $.ajax({
  637. url: "...",
  638. success: callback
  639. });
  640.  
  641. function $http(apiConfig) {
  642. return new Promise(function (resolve, reject) {
  643. var client = new XMLHttpRequest();
  644. client.open(apiConfig.method, apiConfig.url);
  645. client.send();
  646. client.onload = function () {
  647. if (this.status >= 200 && this.status < 300) {
  648. // Performs the function "resolve" when this.status is equal to 2xx.
  649. // Your logic here.
  650. resolve(this.response);
  651. }
  652. else {
  653. // Performs the function "reject" when this.status is different than 2xx.
  654. reject(this.statusText);
  655. }
  656. };
  657. client.onerror = function () {
  658. reject(this.statusText);
  659. };
  660. });
  661. }
  662.  
  663. $http({
  664. method: 'get',
  665. url: 'google.com'
  666. }).then(function(response) {
  667. console.log(response);
  668. }, function(error) {
  669. console.log(error)
  670. });
  671.  
  672. [
  673. "search?type=playlist&q=%22doom%20metal%22",
  674. "search?type=playlist&q=Adele"
  675. ]
  676.  
  677. var ajaxGet = function (ctx,url) {
  678. var res = {};
  679. var ex;
  680. $.ajax(url)
  681. .done(function (data) {
  682. res.data = data;
  683. })
  684. .fail(function(e) {
  685. ex = e;
  686. })
  687. .always(function() {
  688. ctx.resume(ex);
  689. });
  690. return res;
  691. };
  692. ajaxGet.nsynjsHasCallback = true;
  693.  
  694. function process() {
  695. console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
  696. }
  697.  
  698. nsynjs.run(process,this,function () {
  699. console.log("synchronous function finished");
  700. });
  701.  
  702. function foo(result) {
  703. $.ajax({
  704. url: '...',
  705. success: function(response) {
  706. result.response = response; // Store the async result
  707. }
  708. });
  709. }
  710.  
  711. var result = { response: null }; // Object to hold the async result
  712. foo(result); // Returns before the async completes
  713.  
  714. var lat = "";
  715. var lon = "";
  716. function callback(data){
  717. lat = data.lat;
  718. lon = data.lon;
  719. }
  720. function getLoc() {
  721. var url = "http://ip-api.com/json"
  722. $.getJSON(url, function(data) {
  723. callback(data);
  724. });
  725. }
  726.  
  727. getLoc();
  728.  
  729. $(document).ready(function(){
  730. function foo() {
  731. $.ajax({url: "api/data", success: function(data){
  732. fooDone(data); //after we have data, we pass it to fooDone
  733. }});
  734. };
  735.  
  736. function fooDone(data) {
  737. console.log(data); //fooDone has the data and console.log it
  738. };
  739.  
  740. foo(); //call happens here
  741. });
  742.  
  743. async function foo() {
  744. var result = await superagent.get('...')
  745. return result;
  746. }
  747.  
  748. var result = foo();
  749.  
  750. function foo() {
  751. var result;
  752.  
  753. $.ajax({
  754. url: '...',
  755. success: function(response) {
  756. myCallback(response);
  757. }
  758. });
  759.  
  760. return result;
  761. }
  762.  
  763. function myCallback(response) {
  764. // Does something.
  765. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement