Advertisement
Guest User

Untitled

a guest
Jun 30th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.39 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. var app = angular.module('plunker', []);
  422.  
  423. app.controller('MainCtrl', function($scope,$http) {
  424.  
  425. var getJoke = function(){
  426. return $http.get('http://api.icndb.com/jokes/random').then(function(res){
  427. return res.data.value;
  428. });
  429. }
  430.  
  431. getJoke().then(function(res) {
  432. console.log(res.joke);
  433. });
  434. });
  435.  
  436. var async = require("async");
  437.  
  438. // This wires up result back to the caller
  439. var result = {};
  440. var asyncTasks = [];
  441. asyncTasks.push(function(_callback){
  442. // some asynchronous operation
  443. $.ajax({
  444. url: '...',
  445. success: function(response) {
  446. result.response = response;
  447. _callback();
  448. }
  449. });
  450. });
  451.  
  452. async.parallel(asyncTasks, function(){
  453. // result is available after performing asynchronous operation
  454. console.log(result)
  455. console.log('Done');
  456. });
  457.  
  458. // WRONG
  459. var results = [];
  460. theArray.forEach(function(entry) {
  461. doSomethingAsync(entry, function(result) {
  462. results.push(result);
  463. });
  464. });
  465. console.log(results); // E.g., using them, returning them, etc.
  466.  
  467. var results = [];
  468. var expecting = theArray.length;
  469. theArray.forEach(function(entry, index) {
  470. doSomethingAsync(entry, function(result) {
  471. results[index] = result;
  472. if (--expecting === 0) {
  473. // Done!
  474. console.log("Results:", results); // E.g., using the results
  475. }
  476. });
  477. });
  478.  
  479. function doSomethingWith(theArray, callback) {
  480. var results = [];
  481. var expecting = theArray.length;
  482. theArray.forEach(function(entry, index) {
  483. doSomethingAsync(entry, function(result) {
  484. results[index] = result;
  485. if (--expecting === 0) {
  486. // Done!
  487. callback(results);
  488. }
  489. });
  490. });
  491. }
  492. doSomethingWith(theArray, function(results) {
  493. console.log("Results:", results);
  494. });
  495.  
  496. function doSomethingWith(theArray) {
  497. return new Promise(function(resolve) {
  498. var results = [];
  499. var expecting = theArray.length;
  500. theArray.forEach(function(entry, index) {
  501. doSomethingAsync(entry, function(result) {
  502. results[index] = result;
  503. if (--expecting === 0) {
  504. // Done!
  505. resolve(results);
  506. }
  507. });
  508. });
  509. });
  510. }
  511. doSomethingWith(theArray).then(function(results) {
  512. console.log("Results:", results);
  513. });
  514.  
  515. function doSomethingWith(theArray) {
  516. return Promise.all(theArray.map(function(entry) {
  517. return doSomethingAsync(entry, function(result) {
  518. results.push(result);
  519. });
  520. }));
  521. }
  522. doSomethingWith(theArray).then(function(results) {
  523. console.log("Results:", results);
  524. });
  525.  
  526. function doSomethingWith(theArray, callback) {
  527. var results = [];
  528. doOne(0);
  529. function doOne(index) {
  530. if (index < theArray.length) {
  531. doSomethingAsync(theArray[index], function(result) {
  532. results.push(result);
  533. doOne(index + 1);
  534. });
  535. } else {
  536. // Done!
  537. callback(results);
  538. }
  539. }
  540. }
  541. doSomethingWith(theArray, function(results) {
  542. console.log("Results:", results);
  543. });
  544.  
  545. async function doSomethingWith(theArray) {
  546. const results = [];
  547. for (const entry of theArray) {
  548. results.push(await doSomethingAsync(entry));
  549. }
  550. return results;
  551. }
  552. doSomethingWith(theArray).then(results => {
  553. console.log("Results:", results);
  554. });
  555.  
  556. function doSomethingWith(theArray) {
  557. return theArray.reduce(function(p, entry) {
  558. return p.then(function(results) {
  559. return doSomethingAsync(entry).then(function(result) {
  560. results.push(result);
  561. return results;
  562. });
  563. });
  564. }, Promise.resolve([]));
  565. }
  566. doSomethingWith(theArray).then(function(results) {
  567. console.log("Results:", results);
  568. });
  569.  
  570. function doSomethingWith(theArray) {
  571. return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
  572. results.push(result);
  573. return results;
  574. })), Promise.resolve([]));
  575. }
  576. doSomethingWith(theArray).then(results => {
  577. console.log("Results:", results);
  578. });
  579.  
  580. if (!name) {
  581. name = async1();
  582. }
  583. async2(name);
  584.  
  585. async1(name, callback) {
  586. if (name)
  587. callback(name)
  588. else {
  589. doSomething(callback)
  590. }
  591. }
  592.  
  593. async1(name, async2)
  594.  
  595. var Fiber = require('fibers')
  596.  
  597. function async1(container) {
  598. var current = Fiber.current
  599. var result
  600. doSomething(function(name) {
  601. result = name
  602. fiber.run()
  603. })
  604. Fiber.yield()
  605. return result
  606. }
  607.  
  608. Fiber(function() {
  609. var name
  610. if (!name) {
  611. name = async1()
  612. }
  613. async2(name)
  614. // Make any number of async calls from here
  615. }
  616.  
  617. function callback(response) {
  618. // Here you can do what ever you want with the response object.
  619. console.log(response);
  620. }
  621.  
  622. $.ajax({
  623. url: "...",
  624. success: callback
  625. });
  626.  
  627. function $http(apiConfig) {
  628. return new Promise(function (resolve, reject) {
  629. var client = new XMLHttpRequest();
  630. client.open(apiConfig.method, apiConfig.url);
  631. client.send();
  632. client.onload = function () {
  633. if (this.status >= 200 && this.status < 300) {
  634. // Performs the function "resolve" when this.status is equal to 2xx.
  635. // Your logic here.
  636. resolve(this.response);
  637. }
  638. else {
  639. // Performs the function "reject" when this.status is different than 2xx.
  640. reject(this.statusText);
  641. }
  642. };
  643. client.onerror = function () {
  644. reject(this.statusText);
  645. };
  646. });
  647. }
  648.  
  649. $http({
  650. method: 'get',
  651. url: 'google.com'
  652. }).then(function(response) {
  653. console.log(response);
  654. }, function(error) {
  655. console.log(error)
  656. });
  657.  
  658. [
  659. "search?type=playlist&q=%22doom%20metal%22",
  660. "search?type=playlist&q=Adele"
  661. ]
  662.  
  663. var ajaxGet = function (ctx,url) {
  664. var res = {};
  665. var ex;
  666. $.ajax(url)
  667. .done(function (data) {
  668. res.data = data;
  669. })
  670. .fail(function(e) {
  671. ex = e;
  672. })
  673. .always(function() {
  674. ctx.resume(ex);
  675. });
  676. return res;
  677. };
  678. ajaxGet.nsynjsHasCallback = true;
  679.  
  680. function process() {
  681. console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
  682. }
  683.  
  684. nsynjs.run(process,this,function () {
  685. console.log("synchronous function finished");
  686. });
  687.  
  688. function foo(result) {
  689. $.ajax({
  690. url: '...',
  691. success: function(response) {
  692. result.response = response; // Store the async result
  693. }
  694. });
  695. }
  696.  
  697. var result = { response: null }; // Object to hold the async result
  698. foo(result); // Returns before the async completes
  699.  
  700. var lat = "";
  701. var lon = "";
  702. function callback(data){
  703. lat = data.lat;
  704. lon = data.lon;
  705. }
  706. function getLoc() {
  707. var url = "http://ip-api.com/json"
  708. $.getJSON(url, function(data) {
  709. callback(data);
  710. });
  711. }
  712.  
  713. getLoc();
  714.  
  715. $(document).ready(function(){
  716. function foo() {
  717. $.ajax({url: "api/data", success: function(data){
  718. fooDone(data); //after we have data, we pass it to fooDone
  719. }});
  720. };
  721.  
  722. function fooDone(data) {
  723. console.log(data); //fooDone has the data and console.log it
  724. };
  725.  
  726. foo(); //call happens here
  727. });
  728.  
  729. async function foo() {
  730. var result = await superagent.get('...')
  731. return result;
  732. }
  733.  
  734. var result = foo();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement