logo
Tags down

shadow

Why does Typescript think async/await returns a value wrapped in a promise?


By : Pavan Kumar
Date : October 18 2020, 03:08 PM
may help you . Your question "I thought await would return the same value as the first argument in the .then callback. Am I wrong?".
No, you are absolutely right. But you are wrong about what the first argument in the .then callback is.
code :
type IHttpPromise<T> = IPromise<IHttpPromiseCallbackArg<T>>;
handleSubmit(form) {
    const params = this.getParams(form);

    this.myAsyncRequest(params)
       .then((resp:IResp) => this.processResp(resp))
       .catch((e:IServerError) => this.handleError(e));
 }
async handleSubmit(form) {
    const params = this.getParams(form);

    try {
        const httpResp:IHttpPromiseCallbackArg<IResp> = await this.myAsyncRequest(params); 
        const resp: IResp = httpResp.data;
        this.processResp(resp);
    } catch (e:IServerError) {
        this.handleError(e);
    }
}
myAsyncRequest(params:IParams):IHttpPromise<Something> {


Share : facebook icon twitter icon

Using es6-promise with TypeScript 2.1 ES5 Webpack (async/await)


By : ankit goel
Date : March 29 2020, 07:55 AM
To fix the issue you can do You can make the TypeScript compiler aware of ES2015 promises by adding "es2015.promise" to the list of library files to include in your tsconfig.json:
code :
{
    "compilerOptions": {
        "lib": [
            "dom",
            "es5",
            "scripthost",
            "es2015.promise"
        ]
    }
}

How to get the value of a promise in an async / await function on typescript?


By : Yuriy Gorlichenko
Date : March 29 2020, 07:55 AM
hop of those help? key is a string. The return value of getKey, and all async functions, is a promise. You can't assign a promise to a string, as TypeScript is telling you. Instead, you have to wait for the promise (using then) and assign the value of the promise to key. So:
code :
export class AuthService {

  private key:string = "";

  constructor(private storage: Storage) {

  }

  private async getKey() {
    let response = await this.storage.get('key');
    return response;
  }

  public init() {
    this.getKey().then(key => this.key = key);
  }
}
public async init() {
  this.key = await this.getKey();
}
export class AuthService {

  public key: Promise<string>;

  constructor(private storage: Storage) { }

  ngOnInit() { this.key = this.storage.get('key'); }
}

// template

The key is {{key | async}}

Typescript async/await with Observable Or Promise


By : Ankita Agharkar
Date : March 29 2020, 07:55 AM
wish of those help You can use the async functions the way you do but it will have no effect in your example. You have to understand that async function returns a promise:
code :
const fn = async function() {};
fn() instanceof Promise
interval(500)
  .first()
  .map(async (v) => {
    return v;
  })
  .subscribe((v) => {
    console.log(v instanceof Promise); // logs `true`
  });
interval(500)
  .first()
  .map(async (v) => {
    return v;
  })
  .mergeMap((p) => {
    return p;
  })
  .subscribe((v) => {
    console.log(v);
  });

JS async (async/await) returns promise but also executes the function


By : Erhan Biçer
Date : March 29 2020, 07:55 AM
may help you . There are many ways to achieve asynchronosity of code. Callbacks, built-in functions like setTimeout, and Promises are a few of commonly known ones. Marking a function as async is not what makes it truly asynchronous. It allows you to use a keyword await in places where you want to wait on Promises. Yeah, await/async only work with Promise. They are useful for expressing branching and more complex flow control in imperative (sync) style applied to asynchronous code.
Try the following code and see how it works, hope it helps:
code :
function wait(ms, text) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('complete', text);
      resolve({});
    }, ms);
  });
};

async function doTwoThings() {    // This func will return a Promise
  await wait(2000, 'BBB');        // - to which you can subscribe with `.then`
  await wait(1000, 'AAA');        // - or `await` on within another `async` function.
  return 'Both done';
}

doTwoThings()
  .then(
     result => console.info('Done done done!', result),
     err => console.error('Oooops', err)
  );

NodeJS Async/Await doesn't await (returns Promise pending)


By : user2740786
Date : March 29 2020, 07:55 AM
it helps some times You can't use normal "for loop" with Promises, as loop won't wait for a promise to resolve and will move to the next iteration. You can use the new "for of" loop along with async await :-
code :
server.payments()
    .forAccount(accountId)
    .cursor('now')
    .order('desc')
    .limit(2)
    .call()
    .then(async function (page) {
        var history = []

        for(const obj of page.records) {
          const username = await findUser(obj["from"]);
            var payment = {
                "currency":obj["asset_code"],
                "from": obj["from"],
                "username":username,
                "amount": obj["amount"],
                "timestamp":obj["created_at"]
            }
            history.push(payment)
        }

        console.log(history)
        //console.log(JSON.stringify(history))
    })
    .catch((err) => {
        console.log(err)
    })
Related Posts Related Posts :
  • Container's height doesn't be exact as on my screen
  • How to do pagination in Google Firestore?
  • Momentjs strict format always returns 'Invalid date'
  • Is there a api or way to hook into SSRS with a MVC application
  • Can't achieve to beat a ball in my JS Pong Game
  • How do I use composition with es6 classes in the same way as this example does using factory functions?
  • Fetch local JSON file from public folder ReactJS
  • Validate form fields with javascript
  • Jquery detect click OR keystroke?
  • How to change inner div's when cloning a template?
  • Compare two objects and extract the ones that have same Key in javascript
  • Nodejs, Request and Dot notation
  • Array key does not get interpolated when making object
  • Three.js ply not showing
  • Php Ajax Form is not submitting
  • Global Variable and how pass the value in IONIC3
  • Office.js displayDialogAsync throws internal error
  • Is there a shorter way to write Ember computed/get method?
  • How can I display/hide a component depending on a property on the Redux store?
  • Range Selector - Changing bar color only when active
  • Creating a new array of objects by finding values in JSON data
  • How to avoid providing a dummy Vue data structure during initialization?
  • Digital time to readable duration using javascript
  • JavaScript update outside function variable from inner function
  • Update a document with mongoose (update property of document property)
  • Highcharts' bullet graph's serie's doesn't extend all the way
  • 2 way-binding with a nested property inside object. (VueJS + VueX)
  • Angular uiCalendar not redenring events
  • Use blade inside a JavaScript variable
  • Group objects by multiple properties in array then sum up their values
  • Electron: Maximized browserWindow overlaps Window' taskbar
  • Mongoose deep populate results in [Object] at 2nd level
  • Redux: cloning state does not work
  • angularjs detect changes in input when value is modified by JQuery
  • How to release a file after accessing it with JavaScript (adobe)
  • Handle/catch errors without repeating code?
  • Filter search Results
  • How to efficiently add items to collection with firebase firestore
  • Change Bootstrap Popover trigger on Click
  • Pushing new objects replaces previous object
  • Function with dynamic return in typescript
  • How Do I bind javascript type of File to a Nancy Model containing HttpFile?
  • Simplifying jquery / javascript for checkbox links
  • Javascript ES6 Classes composition
  • Chart.js max legend height
  • Change color of a styled checked checkbox with button
  • How to set weight and height in Css with responsive when reduce screen size
  • Price formatting and user input value to change slider
  • Pass params to q.defer (d3.csv)
  • Combine a textfield and TinyMCE field to a third field with JavaScript. Constrain TinyMCE to Numbered List
  • Javascript regex to match alpha length followed by number length
  • Pass props from child to parent react navigation
  • How to share redux store in multiple components
  • Javascript Regex Expression Not Returning Expected Value
  • with draft.js is it possible to create a custom block span with classname
  • How to convert Javascript object to a url string?
  • Adobe Javascript in Action Wizard vs a form button
  • Filtering Tooltip in Kendo
  • How to update a grouped bar-chart in d3js
  • Javascript ES6 custom sort method not working all the times
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com