logo
down
shadow

Calling asynchronous function but returning result synchronously


Calling asynchronous function but returning result synchronously

By : Alejandro Monroy
Date : October 18 2020, 06:10 AM
wish help you to fix your issue I want to construct a function that creates and returns an Observable. Depending on the parameters this function receives it should either create the Observable and return it directly or (in a special case) call another asynchronous function before returning the Observable. ,
Is there any way to solve this problem?
code :
function returnObservable(specialCase: boolean): Observable<any>
    const promise = specialCase ? doSomethingAsync() : Promise.resolve();
    const observable = new Observable(
        observer => {
            promise
            .then(() => {
                observer.next(1);
            })
            .catch(error => {
                // deal with the error
            });
        }
    );

    return observable;
} 


Share : facebook icon twitter icon
Meteor: Calling an asynchronous function inside a Meteor.method and returning the result

Meteor: Calling an asynchronous function inside a Meteor.method and returning the result


By : Lauren Weeks
Date : March 29 2020, 07:55 AM
this one helps. Andrew Mao is right. Meteor now has Meteor.wrapAsync() for this kind of situation.
Here's the simplest way to do a charge via stripe and also pass a callback function:
code :
var stripe = StripeAPI("key");    
Meteor.methods({

    yourMethod: function(callArg) {

        var charge = Meteor.wrapAsync(stripe.charges.create, stripe.charges);
        charge({
            amount: amount,
            currency: "usd",
            //I passed the stripe token in callArg
            card: callArg.stripeToken,
        }, function(err, charge) {
            if (err && err.type === 'StripeCardError') {
              // The card has been declined
              throw new Meteor.Error("stripe-charge-error", err.message);
            }

            //Insert your 'on success' code here

        });
    }
});
Node.js return result of multiple asynchronous yield synchronously

Node.js return result of multiple asynchronous yield synchronously


By : Pierre Bittner
Date : March 29 2020, 07:55 AM
I wish did fix the issue. So I asked the same question on the reThinkDB google groups :
To quote Ryan Paul :
code :
function myFn() {
  return co(function*() {
    var conn = yield r.connect();
    var query1 = yield r.db("test").table("fellowship")
                        .filter({species: "hobbit"})
                        .coerceTo("array").run(conn);

    var query2 = yield r.db("test").table("fellowship")
                        .filter({species: "human"})
                        .coerceTo("array").run(conn);

    conn.close();

    return {q1: query1, q2: query2};
  });
}
function myFn1() {
  return r.connect().then(conn => {
    return bluebird.all([
      r.db("test").table("fellowship")
       .filter({species: "hobbit"})
       .coerceTo("array").run(conn),
      r.db("test").table("fellowship")
       .filter({species: "human"})
       .coerceTo("array").run(conn)
    ]).then(items => ({q1: items[0], q2: items[1]}));
  });
}
Use (asynchronous) $http result to (synchronously) check permissions on routes

Use (asynchronous) $http result to (synchronously) check permissions on routes


By : Tom Eichman
Date : March 29 2020, 07:55 AM
wish of those help I'm trying to check permissions on routes in an AngularJS application. Routes are handled by angular-ui-router. , In your protected state's definition:
code :
.state('root.some_page', {
            url: '/',
            templateUrl: 'some_page.html',
            controller: 'home',
            resolve: {
             access: function($http, $state){ //Note: you can inject your own services/factories too
             var requiredPermissions = ['some_right', 'some_other_right'];
              return $http.get(...).then(function(response){
               var permissions = response.data.permissions;
               var granted = permissions.reduce((prev,curr) => requiredPermissions.indexOf(curr) > -1 || prev, false);
               if(!granted)
                $state.go('publicState');
               return permissions;
              });
             }
            }
        })
function checkPermissions(requiredPermissions){
 return function ($http, $state){ //Note: you can inject your own services/factories too
              return $http.get(...).then(function(response){
               var permissions = response.data.permissions;
               var granted = permissions.reduce((prev,curr) => requiredPermissions.indexOf(curr) > -1 || prev, false);
               if(!granted)
                $state.go('publicState');
               return permissions;
              });
             }
 }

 //In state definition
.state('root.some_page', {
        url: '/',
        templateUrl: 'some_page.html',
        controller: 'home',
        resolve: {
         access: checkPermissions(['first','second'])
        }
    })
Returning asynchronous data then exporting it synchronously in Node.js

Returning asynchronous data then exporting it synchronously in Node.js


By : user1936523
Date : March 29 2020, 07:55 AM
Any of those help Because the needed data is gotten asynchronously, there's no way around making everything that depends on it (somehow) asynchronous as well. With asynchronicity involved, one possibility is to usually export functions that can be called on demand, rather than exporting objects:
an object that depends on the asynchronous data can't be meaningfully exported before the data comes back if you export functions rather than objects, you can ensure that control flow starts from your single entry point and heads downstream, rather than every module initializing itself at once (which can be problematic when some modules depend on others to be initialized properly, as you're seeing)
code :
const promise = require('../secrets');

(async () => {
  // try/catch is needed to handle rejected promises when using await:
  try {
    const secrets = await promise;
    // use secrets here
  } catch(e) {
    // handle errors
  }
})();
const promise = require('../secrets');

promise
  .then((secrets) => {
    // use secrets here
  })
  .catch((err) => {
    // handle errors
  });
// note, secrets is *not* imported
function makePool(secrets) {
  const pool = new Pool({
    user: secrets.dbUsername,
    host: secrets.dbHost,
    database: secrets.dbDatabase,
    password: secrets.dbPassword,
    port: secrets.dbPort
  });

  pool.on('error', err => {
    console.error('Unexpected error on idle client', err);
    process.exit(-1);
  });
  return pool;
}

module.exports = makePool;
const secretsProm = require('../secrets');
const makePool = require('./makePool');
secretsProm.then((secrets) => {
  const pool = makePool(secrets);
  doSomethingWithPool(pool);
})
.catch((err) => {
  // handle errors
});
loop synchronously through array while calling asynchronous function

loop synchronously through array while calling asynchronous function


By : Alastair Dallas
Date : March 29 2020, 07:55 AM
I wish this helpful for you You can map over your user array to create an array of promises. Use Promise.all to wait for those promises to resolve and then iterate over the responses to check whether the hash matches the id.
In this example I've used async/await. I've also mocked up a hashing function routine so you can see it in action. Simply change the resolve from 'id' to 'id + 1' and rerun the demo to see the Match become No match.
code :
const safety_first = {
  getUserHash(id) {
    return new Promise(resolve => {
      setTimeout(() => resolve(id), 1000);
    });
  }
}

async function checkUserHashes(userList, promises) {
  try {

    // await the promises to all resolve
    // `Promise.all` preserves the order...
    const res = await Promise.all(promises);

    // ...which makes it useful if you need to check the returned
    // results against the promise-producing array
    userList.forEach(({ id }, i) => {
      if (id === res[i]) console.log(`${id}|${res[i]} - Match`);
      if (id !== res[i]) console.log(`${id}|${res[i]} - No match`);
    });

  } catch (e) {
    console.log(e);
  }
};

const userList = [{ id: 1, userHash: 1 }, { id: 2, userHash: 2 }];

// `map` over the fields and return a
// validation promise for each
const promises = userList.map(({ id }) => {
  return safety_first.getUserHash(id);
});

// Pass in the original userList, and the generated promises
checkUserHashes(userList, promises);
const safety_first = {
  getUserHash(id) {
    return new Promise(resolve => {

      // This will match the second object (index 1)
      setTimeout(() => resolve(id === 1 ? id: id + 1), 1000);
    });
  }
}

async function checkUserHashes(userList) {

  // iterate over the array of objects
  for (let [index, obj] of userList.entries()) {

    // await for that one hash check
    const res = await safety_first.getUserHash(obj.id);

    // if it matches return the id
    if (obj.id === res) return obj;
  }

  // otherwise return null if there are no matches
  return null;
}

const userList = [{ id: 0, userHash: 1 }, { id: 1, userHash: 2 }];

(async () => {
  const id = await checkUserHashes(userList);
  console.log(id);
})();
Related Posts Related Posts :
  • get raw text from textarea
  • D3 zoom v3 vs v5
  • How to use NOR gate in JavaScript?
  • Fix Nav Bar after scroll
  • HTML hyperlink not calling JavaScript function
  • List of All Background Images in DOM
  • Using jsAnim.js
  • How to check if XMLHttpRequest's send() supports File
  • Is there a Javascript cron implementation somewhere that I'm missing?
  • Is there any gmap’s api function to concatenate address string from AddressDetails structure?
  • Could not set the selected property JQuery. JQuery Dropdown
  • Jquery making div fadeout with timer
  • Browser EventListenerList Implementation
  • Shopping cart using OO javascript
  • Getting error while running simple javascript using node framework
  • using jquery, How to redirect when drop down list selection changes?
  • Javascript Not Parsing Nested Bbcode
  • run function at ready and keyup event
  • Set field in mongoose document to array length
  • disable Double tap zoom/resize on safari IOS12***
  • how to add a wait in time in a for ..of?
  • Time Spent by user on a web page + Iframe
  • animate.css is not working in Chrome latest version (Version above 73)
  • Row selection and pagination - Vue
  • How can I use function chaining with dates in JavaScript?
  • What is the difference between "delete" and "Reflect.deleteProperty()"
  • How to get attributes of individual elements in jquery array
  • Why do I get different results with "=" vs. "===" in javascript with Conditional (Ternary) Operators
  • I am trying to hold value of document.getElementById("image").src=UserInput +".gif"
  • Array being pushed into another array isn't displaying
  • Is there a React.js NPM module or any other solution for image/object mutli-selection?
  • 80% Javascript Solution for Flags in Codility
  • I want to display background while scrolling down
  • RegEx for matching text between two tags
  • Does having a lot of inner 'helper' functions inside a functional stateless react component will result in worse perform
  • How to submit a form through a button outside the form?
  • ESLint: Use callback in setState when referencing the previous state
  • How to parse state from one component to another in my example?
  • Visible Html select option showing under hidden items
  • Create SVG circle using path with 6 segments
  • Getting error while reading from a text file
  • Read a value from JSON Array without entity
  • Checkbox check or uncheck value null
  • Displaying multiple slider values to users
  • Am doing the destructing right?
  • VueJS data-bind object styling not working
  • Combine array and object destructuring
  • Execution skips promise statements
  • sort an array of objects leaving first field
  • how to highlight table cells in a certain way when hover over
  • Problems when using Chosen Selectors in external helper functions
  • Need to merge two objects together that each have an array to the matching IDs
  • How to get previous 6 months date from current date in javascript
  • how to get object value only without mentioning key from array list using ngFor in angular 7
  • Plugging into on_page_change events in testcafe
  • WithStore: Cannot read property 'state' of undefined (pure-react-carousel)
  • fullcalendar event info in modal popup
  • How do i reduce time complexity of this code
  • Deep comparing object props in React not working as expected
  • JavaScript method to remove case insensitive duplicates from string/Numbers
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk