Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function foo() {
- var result;
- $.ajax({
- url: '...',
- success: function(response) {
- result = response;
- // return response; // <- I tried that one as well
- }
- });
- return result;
- }
- var result = foo(); // It always ends up being `undefined`.
- function findItem() {
- var item;
- while(item_not_found) {
- // search
- }
- return item;
- }
- var item = findItem();
- // Do something with item
- doSomethingElse();
- findItem(function(item) {
- // Do something with item
- });
- doSomethingElse();
- // Using 'superagent' which will return a promise.
- var superagent = require('superagent')
- // This is isn't declared as `async` because it already returns a promise
- function delay() {
- // `delay` returns a promise
- return new Promise(function(resolve, reject) {
- // Only `delay` is able to resolve or reject the promise
- setTimeout(function() {
- resolve(42); // After 3 seconds, resolve the promise with value 42
- }, 3000);
- });
- }
- async function getAllBooks() {
- try {
- // GET a list of book IDs of the current user
- var bookIDs = await superagent.get('/user/books');
- // wait for 3 seconds (just for the sake of this example)
- await delay();
- // GET information about each book
- return await superagent.get('/books/ids='+JSON.stringify(bookIDs));
- } catch(error) {
- // If any of the awaited promises was rejected, this catch block
- // would catch the rejection reason
- return null;
- }
- }
- // Async functions always return a promise
- getAllBooks()
- .then(function(books) {
- console.log(books);
- });
- var result = foo();
- // Code that depends on 'result'
- foo(function(result) {
- // Code that depends on 'result'
- });
- function myCallback(result) {
- // Code that depends on 'result'
- }
- foo(myCallback);
- function foo(callback) {
- $.ajax({
- // ...
- success: callback
- });
- }
- function foo(callback) {
- $.ajax({
- // ...
- success: function(response) {
- // For example, filter the response
- callback(filtered_response);
- }
- });
- }
- function delay() {
- // `delay` returns a promise
- return new Promise(function(resolve, reject) {
- // Only `delay` is able to resolve or reject the promise
- setTimeout(function() {
- resolve(42); // After 3 seconds, resolve the promise with value 42
- }, 3000);
- });
- }
- delay()
- .then(function(v) { // `delay` returns a promise
- console.log(v); // Log the value once it is resolved
- })
- .catch(function(v) {
- // Or do something else if it is rejected
- // (it would not happen in this example, since `reject` is not called).
- });
- function ajax(url) {
- return new Promise(function(resolve, reject) {
- var xhr = new XMLHttpRequest();
- xhr.onload = function() {
- resolve(this.responseText);
- };
- xhr.onerror = reject;
- xhr.open('GET', url);
- xhr.send();
- });
- }
- ajax("/echo/json")
- .then(function(result) {
- // Code depending on result
- })
- .catch(function() {
- // An error occurred
- });
- function ajax() {
- return $.ajax(...);
- }
- ajax().done(function(result) {
- // Code depending on result
- }).fail(function() {
- // An error occurred
- });
- function checkPassword() {
- return $.ajax({
- url: '/password',
- data: {
- username: $('#username').val(),
- password: $('#password').val()
- },
- type: 'POST',
- dataType: 'json'
- });
- }
- if (checkPassword()) {
- // Tell the user they're logged in
- }
- checkPassword()
- .done(function(r) {
- if (r) {
- // Tell the user they're logged in
- } else {
- // Tell the user their password was bad
- }
- })
- .fail(function(x) {
- // Tell the user something bad happened
- });
- function foo() {
- var jqXHR = $.ajax({
- //...
- async: false
- });
- return jqXHR.responseText;
- }
- function foo() {
- var httpRequest = new XMLHttpRequest();
- httpRequest.open('GET', "/echo/json");
- httpRequest.send();
- return httpRequest.responseText;
- }
- var result = foo(); // always ends up being 'undefined'
- function getFive(){
- var a;
- setTimeout(function(){
- a=5;
- },10);
- return a;
- }
- function onComplete(a){ // When the code completes, do this
- alert(a);
- }
- function getFive(whenDone){
- var a;
- setTimeout(function(){
- a=5;
- whenDone(a);
- },10);
- }
- getFive(onComplete);
- var request = new XMLHttpRequest();
- request.open('GET', 'yourURL', false); // `false` makes the request synchronous
- request.send(null);
- if (request.status === 200) {// That's HTTP for 'ok'
- console.log(request.responseText);
- }
- var result = foo();
- // code that depends on `result` goes here
- foo(function(result) {
- // code that depends on `result`
- });
- function myHandler(result) {
- // code that depends on `result`
- }
- foo(myHandler);
- function foo(callback) {
- var httpRequest = new XMLHttpRequest();
- httpRequest.onload = function(){ // when the request is loaded
- callback(httpRequest.responseText);// we're calling our method
- };
- httpRequest.open('GET', "/echo/json");
- httpRequest.send();
- }
- function ajax(a, b, c){ // URL, callback, just a placeholder
- c = new XMLHttpRequest;
- c.open('GET', a);
- c.onload = b;
- c.send()
- }
- this.response
- e.target.response
- function callback(e){
- console.log(this.response);
- }
- ajax('URL', callback);
- ajax('URL', function(e){console.log(this.response)});
- function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
- c = new XMLHttpRequest;
- c.open(e||'get', a);
- c.onload = b;
- c.send(d||null)
- }
- x(url, callback); // By default it's get so no need to set
- x(url, callback, 'post', {'key': 'val'}); // No need to set post data
- var fd = new FormData(form);
- x(url, callback, 'post', fd);
- var fd = new FormData();
- fd.append('key', 'val')
- x(url, callback, 'post', fd);
- function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
- c = new XMLHttpRequest;
- c.open(e||'get', a);
- c.onload = b;
- c.onerror = error;
- c.send(d||null)
- }
- function error(e){
- console.log('--Error--', this.type);
- console.log('this: ', this);
- console.log('Event: ', e)
- }
- function displayAjax(e){
- console.log(e, this);
- }
- x('WRONGURL', displayAjax);
- function omg(a, c){ // URL
- c = new XMLHttpRequest;
- c.open('GET', a, true);
- c.send();
- return c; // Or c.response
- }
- var res = omg('thisIsGonnaBlockThePage.txt');
- function foo() {
- var data;
- // or $.get(...).then, or request(...).then, or query(...).then
- fetch("/echo/json").then(function(response){
- data = response.json();
- });
- return data;
- }
- var result = foo(); // result is always undefined no matter what.
- function delay(ms){ // takes amount of milliseconds
- // returns a new promise
- return new Promise(function(resolve, reject){
- setTimeout(function(){ // when the time is up
- resolve(); // change the promise to the fulfilled state
- }, ms);
- });
- }
- function foo() {
- // RETURN the promise
- return fetch("/echo/json").then(function(response){
- return response.json(); // process it inside the `then`
- });
- }
- foo().then(function(response){
- // access the value inside the `then`
- })
- function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
- yield 1;
- yield 2;
- while(true) yield 3;
- }
- var foo = coroutine(function*(){
- var data = yield fetch("/echo/json"); // notice the yield
- // code here only executes _after_ the request is done
- return data.json(); // data is defined
- });
- var main = coroutine(function*(){
- var bar = yield foo(); // wait our earlier coroutine, it returns a promise
- // server call done here, code below executes when done
- var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
- console.log(baz); // runs after both requests done
- });
- main();
- async function foo(){
- var data = await fetch("/echo/json"); // notice the await
- // code here only executes _after_ the request is done
- return data.json(); // data is defined
- }
- function handleData( responseData ) {
- // Do what you want with the data
- console.log(responseData);
- }
- $.ajax({
- url: "hi.php",
- ...
- success: function ( data, status, XHR ) {
- handleData(data);
- }
- });
- function callServerAsync(){
- $.ajax({
- url: '...',
- success: function(response) {
- successCallback(response);
- }
- });
- }
- function successCallback(responseObj){
- // Do something like read the response and show data
- alert(JSON.stringify(responseObj)); // Only applicable to JSON response
- }
- function foo(callback) {
- $.ajax({
- url: '...',
- success: function(response) {
- return callback(null, response);
- }
- });
- }
- var result = foo(function(err, result){
- if (!err)
- console.log(result);
- });
- promiseB = promiseA.then(
- function onSuccess(result) {
- return result + 1;
- }
- ,function onError(err) {
- //Handle error
- }
- );
- // promiseB will be resolved immediately after promiseA is resolved
- // and its value will be the result of promiseA incremented by 1.
- search(term: string) {
- return this.http
- .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
- .map((response) => response.json())
- .toPromise();
- search() {
- this.searchService.search(this.searchField.value)
- .then((result) => {
- this.result = result.artists.items;
- })
- .catch((error) => console.error(error));
- }
- // WRONG
- var results = [];
- theArray.forEach(function(entry) {
- doSomethingAsync(entry, function(result) {
- results.push(result);
- });
- });
- console.log(results); // E.g., using them, returning them, etc.
- var results = [];
- var expecting = theArray.length;
- theArray.forEach(function(entry, index) {
- doSomethingAsync(entry, function(result) {
- results[index] = result;
- if (--expecting === 0) {
- // Done!
- console.log("Results:", results); // E.g., using the results
- }
- });
- });
- function doSomethingWith(theArray, callback) {
- var results = [];
- var expecting = theArray.length;
- theArray.forEach(function(entry, index) {
- doSomethingAsync(entry, function(result) {
- results[index] = result;
- if (--expecting === 0) {
- // Done!
- callback(results);
- }
- });
- });
- }
- doSomethingWith(theArray, function(results) {
- console.log("Results:", results);
- });
- function doSomethingWith(theArray) {
- return new Promise(function(resolve) {
- var results = [];
- var expecting = theArray.length;
- theArray.forEach(function(entry, index) {
- doSomethingAsync(entry, function(result) {
- results[index] = result;
- if (--expecting === 0) {
- // Done!
- resolve(results);
- }
- });
- });
- });
- }
- doSomethingWith(theArray).then(function(results) {
- console.log("Results:", results);
- });
- function doSomethingWith(theArray) {
- return Promise.all(theArray.map(function(entry) {
- return doSomethingAsync(entry, function(result) {
- results.push(result);
- });
- }));
- }
- doSomethingWith(theArray).then(function(results) {
- console.log("Results:", results);
- });
- function doSomethingWith(theArray, callback) {
- var results = [];
- doOne(0);
- function doOne(index) {
- if (index < theArray.length) {
- doSomethingAsync(theArray[index], function(result) {
- results.push(result);
- doOne(index + 1);
- });
- } else {
- // Done!
- callback(results);
- }
- }
- }
- doSomethingWith(theArray, function(results) {
- console.log("Results:", results);
- });
- async function doSomethingWith(theArray) {
- const results = [];
- for (const entry of theArray) {
- results.push(await doSomethingAsync(entry));
- }
- return results;
- }
- doSomethingWith(theArray).then(results => {
- console.log("Results:", results);
- });
- function doSomethingWith(theArray) {
- return theArray.reduce(function(p, entry) {
- return p.then(function(results) {
- return doSomethingAsync(entry).then(function(result) {
- results.push(result);
- return results;
- });
- });
- }, Promise.resolve([]));
- }
- doSomethingWith(theArray).then(function(results) {
- console.log("Results:", results);
- });
- function doSomethingWith(theArray) {
- return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
- results.push(result);
- return results;
- })), Promise.resolve([]));
- }
- doSomethingWith(theArray).then(results => {
- console.log("Results:", results);
- });
- var app = angular.module('plunker', []);
- app.controller('MainCtrl', function($scope,$http) {
- var getJoke = function(){
- return $http.get('http://api.icndb.com/jokes/random').then(function(res){
- return res.data.value;
- });
- }
- getJoke().then(function(res) {
- console.log(res.joke);
- });
- });
- var async = require("async");
- // This wires up result back to the caller
- var result = {};
- var asyncTasks = [];
- asyncTasks.push(function(_callback){
- // some asynchronous operation
- $.ajax({
- url: '...',
- success: function(response) {
- result.response = response;
- _callback();
- }
- });
- });
- async.parallel(asyncTasks, function(){
- // result is available after performing asynchronous operation
- console.log(result)
- console.log('Done');
- });
- $(document).ready(function(){
- function foo() {
- $.ajax({url: "api/data", success: function(data){
- fooDone(data); //after we have data, we pass it to fooDone
- }});
- };
- function fooDone(data) {
- console.log(data); //fooDone has the data and console.log it
- };
- foo(); //call happens here
- });
- if (!name) {
- name = async1();
- }
- async2(name);
- async1(name, callback) {
- if (name)
- callback(name)
- else {
- doSomething(callback)
- }
- }
- async1(name, async2)
- var Fiber = require('fibers')
- function async1(container) {
- var current = Fiber.current
- var result
- doSomething(function(name) {
- result = name
- fiber.run()
- })
- Fiber.yield()
- return result
- }
- Fiber(function() {
- var name
- if (!name) {
- name = async1()
- }
- async2(name)
- // Make any number of async calls from here
- }
- function callback(response) {
- // Here you can do what ever you want with the response object.
- console.log(response);
- }
- $.ajax({
- url: "...",
- success: callback
- });
- [
- "search?type=playlist&q=%22doom%20metal%22",
- "search?type=playlist&q=Adele"
- ]
- -H "Authorization: Bearer {your access token}"
- function $http(apiConfig) {
- return new Promise(function (resolve, reject) {
- var client = new XMLHttpRequest();
- client.open(apiConfig.method, apiConfig.url);
- client.send();
- client.onload = function () {
- if (this.status >= 200 && this.status < 300) {
- // Performs the function "resolve" when this.status is equal to 2xx.
- // Your logic here.
- resolve(this.response);
- }
- else {
- // Performs the function "reject" when this.status is different than 2xx.
- reject(this.statusText);
- }
- };
- client.onerror = function () {
- reject(this.statusText);
- };
- });
- }
- $http({
- method: 'get',
- url: 'google.com'
- }).then(function(response) {
- console.log(response);
- }, function(error) {
- console.log(error)
- });
- (async function(){
- var response = await superagent.get('...')
- console.log(response)
- })()
- var ajaxGet = function (ctx,url) {
- var res = {};
- var ex;
- $.ajax(url)
- .done(function (data) {
- res.data = data;
- })
- .fail(function(e) {
- ex = e;
- })
- .always(function() {
- ctx.resume(ex);
- });
- return res;
- };
- ajaxGet.nsynjsHasCallback = true;
- function process() {
- console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
- }
- nsynjs.run(process,this,function () {
- console.log("synchronous function finished");
- });
- function doAjax(callbackFunc, method, url) {
- var xmlHttpReq = new XMLHttpRequest();
- xmlHttpReq.open(method, url);
- xmlHttpReq.onreadystatechange = function() {
- if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
- callbackFunc(xmlHttpReq.responseText);
- }
- }
- xmlHttpReq.send(null);
- }
- function loadMyJson(categoryValue){
- if(categoryValue==="veg")
- doAjax(print,"GET","http://localhost:3004/vegetables");
- else if(categoryValue==="fruits")
- doAjax(print,"GET","http://localhost:3004/fruits");
- else
- console.log("Data not found");
- }
- function foo(){
- // do something
- return 'wohoo';
- }
- let bar = foo(); // bar is 'wohoo' here
- function foo(){
- setTimeout( ()=>{
- return 'wohoo';
- }, 1000 )
- }
- let bar = foo() // bar is undefined here
- function foo(){
- return new Promise( (resolve, reject) => { // I want foo() to PROMISE me something
- setTimeout ( function(){
- // promise is RESOLVED , when execution reaches this line of code
- resolve('wohoo')// After 1 second, RESOLVE the promise with value 'wohoo'
- }, 1000 )
- })
- }
- let bar ;
- foo().then( res => {
- bar = res;
- console.log(bar) // will print 'wohoo'
- });
- function fetchUsers(){
- let users = [];
- getUsers()
- .then(_users => users = _users)
- .catch(err =>{
- throw err
- })
- return users;
- }
- async function fetchUsers(){
- try{
- let users = await getUsers()
- return users;
- }
- catch(err){
- throw err;
- }
- }
- var lat = "";
- var lon = "";
- function callback(data) {
- lat = data.lat;
- lon = data.lon;
- }
- function getLoc() {
- var url = "http://ip-api.com/json"
- $.getJSON(url, function(data) {
- callback(data);
- });
- }
- getLoc();
- function* myGenerator() {
- const callback = yield;
- let [response] = yield $.ajax("https://stackoverflow.com", {complete: callback});
- console.log("response is:", response);
- // examples of other things you can do
- yield setTimeout(callback, 1000);
- console.log("it delayed for 1000ms");
- while (response.statusText === "error") {
- [response] = yield* anotherGenerator();
- }
- }
- const gen = myGenerator(); // Create generator
- gen.next(); // Start it
- gen.next((...args) => gen.next([...args])); // Set its callback function
- const [err, data] = yield fs.readFile(filePath, "utf-8", callback);
- function foo(result) {
- $.ajax({
- url: '...',
- success: function(response) {
- result.response = response; // Store the async result
- }
- });
- }
- var result = { response: null }; // Object to hold the async result
- foo(result); // Returns before the async completes
- function foo() {
- var result;
- $.ajax({
- url: '...',
- success: function(response) {
- myCallback(response);
- }
- });
- return result;
- }
- function myCallback(response) {
- // Does something.
- }
- __pragma__ ('alias', 'S', '$')
- def read(url: str):
- deferred = S.Deferred()
- S.ajax({'type': "POST", 'url': url, 'data': { },
- 'success': lambda d: deferred.resolve(d),
- 'error': lambda e: deferred.reject(e)
- })
- return deferred.promise()
- async def readALot():
- try:
- result1 = await read("url_1")
- result2 = await read("url_2")
- except Exception:
- console.warn("Reading a lot failed")
- var milk = order_milk();
- put_in_coffee(milk);
- order_milk(put_in_coffee);
- order_milk(function(milk) { put_in_coffee(milk, drink_coffee); }
- var answer;
- $.ajax('/foo.json') . done(function(response) {
- callback(response.data);
- });
- function callback(data) {
- console.log(data);
- }
- order_milk() . then(put_in_coffee)
- order_milk() . then(put_in_coffee) . then(drink_coffee)
- function get_data() {
- return $.ajax('/foo.json');
- }
- get_data() . then(do_something)
- get_data() .
- then(function(data) { console.log(data); });
- get_data() .
- then(data => console.log(data));
- a();
- b();
- a() . then(b);
- async function morning_routine() {
- var milk = await order_milk();
- var coffee = await put_in_coffee(milk);
- await drink(coffee);
- }
- async function foo() {
- data = await get_data();
- console.log(data);
- }
- async function foo() {
- var response = await $.ajax({url: '...'})
- return response;
- }
- (async function() {
- try {
- var result = await foo()
- console.log(result)
- } catch (e) {}
- })()
- foo().then(response => {
- console.log(response)
- }).catch(error => {
- console.log(error)
- })
- while (queue.waitForMessage()) {
- queue.processNextMessage();
- }
- 1. call foo.com/api/bar using foobarFunc
- 2. Go perform an infinite loop
- ... and so on
- function foobarFunc (var) {
- console.log(anotherFunction(var));
- }
- function foo(bla) {
- console.log(bla)
- }
Add Comment
Please, Sign In to add comment